简体   繁体   English

在DataGridView中设置ComboBox的默认选定值

[英]Set default selected value of ComboBox in DataGridView

My Form consist of a DataGridView and, inside of that, I have one Column as ComboBox. 我的表单包含一个DataGridView,在其中,我有一个列作为ComboBox。
The ComboBox is getting filled by the database query. ComboBox被数据库查询填充。

I wanted to display the default value of ComboBox in the DataGridView. 我想在DataGridView中显示ComboBox的默认值。 I have loaded values in combo box but could not find a way to set a default value for that. 我已经在组合框中加载了值,但是找不到一种方法来为其设置默认值。

布局

I have added values to a combo box with the following code on the click of the btnLoadCombo button: 单击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();            
 }

I expect results as shown in image 2. 我期望结果如图2所示。

You can use 您可以使用

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
}

You are going through every row with the foreach() loop and compare the value of Cat_ParentCat with row.Cells[3].Value.Equals(Cat_ParentCatValue) . 您将使用foreach()循环foreach()每一行,并将Cat_ParentCat的值与row.Cells[3].Value.Equals(Cat_ParentCatValue) If a match is found, set the default value of the ComboBox with row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue]; 如果找到匹配项,则使用row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];设置ComboBox的默认值row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM