【问题标题】:Set default selected value of ComboBox in DataGridView在 DataGridView 中设置 ComboBox 的默认选定值
【发布时间】:2019-01-13 15:42:47
【问题描述】:

我的表单由一个 DataGridView 组成,在其中,我有一个 Column 作为 ComboBox。
ComboBox 正在被数据库查询填充。

我想在 DataGridView 中显示 ComboBox 的默认值。我已经在组合框中加载了值,但找不到为其设置默认值的方法。

我在单击btnLoadCombo 按钮时使用以下代码向组合框添加了值:

private void btnLoadCombo_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);

    //Filling ComboBoxes
    con.Open();
    SqlCommand cmdGetRootCat = new SqlCommand("SELECT * FROM tblProductCategories", con);

    SqlDataReader sdaRootCat = cmdGetRootCat.ExecuteReader();
    comboBoxCatTest.Items.Clear();

    while (sdaRootCat.Read())
    {
        this.CatCombo.Items.Add(sdaRootCat["Cat_Name"]);
    }

    //Filling DataGridView
    DataTable dt = new DataTable();
    dt.Clear();
    SqlCommand cmd = new SqlCommand("SELECT Cat_ID, Cat_Name FROM tblProductCategories", con);

    SqlDataReader sda = cmd.ExecuteReader();
    dt.Load(sda);
    dataGridCatList.DataSource = dt;
    con.Close();            
 }

我希望结果如图 2 所示。

【问题讨论】:

  • 你可以使用dataGridCatList.Rows[0].Cells[0].Value = this.CatCombo.Items[yourDefaultValue]这会将你的第一个单元格的默认值设置为选定的默认值
  • 没有结果...先生,请检查我的附件图片以了解我想要什么。谢谢。
  • 指出这仅适用于第一个单元格
  • 是的,现在正在显示。

标签: c# winforms datagridview


【解决方案1】:

你可以使用

foreach(DataGridViewRow row in dataGridCatList.Rows)
{
    if(row.Cells[3].Value != null) //ignore last row which is empty
    {
        if( row.Cells[3].Value.Equals(1018) )
            row.Cells[0].Value = this.CatCombo.Items[0];
    }
    //...and so on
}

您正在使用foreach() 循环遍历每一行,并将Cat_ParentCat 的值与row.Cells[3].Value.Equals(Cat_ParentCatValue) 进行比较。如果找到匹配项,则将 ComboBox 的默认值设置为 row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 2015-11-14
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2016-08-05
    相关资源
    最近更新 更多