如何使用C#在datagridview Windows Forms应用程序内的ComboBox中设置默认第一个值

时间:2019-05-04 07:12:39

标签: c# winforms datagridview combobox

我的Windows窗体应用程序具有带组合框的Datagridview,我需要设置例如第一个值(“选择项目”)

我的结果

My result is.

预期结果

Expected Result



DataGridViewComboBoxColumn cmd_item =(DataGridViewComboBoxColumn)(invoice_datagrid.Columns["cmb_gridItem"]);
            DataTable dt = new DataTable();
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT DISTINCT  item_name,sales_rate.item_id FROM sales_rate JOIN items ON sales_rate.item_id=items.item_id", con);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(dt);
            cmd_item.DisplayMember = "item_name";
            cmd_item.ValueMember = "item_id";
            cmd_item.DataSource = dt;
            con.Close();



1 个答案:

答案 0 :(得分:1)

首先,您需要在数据库中为选择项文本

添加一个条目
....
da.SelectCommand = cmd;
da.Fill(dt);

// Add a fake record to the table with id = -1 to recognize it 
DataRow r = dt.NewRow();
r.ItemArray = new object[] {"select item", -1};

// Insert the new row in the first position of your table
dt.Rows.InsertAt(r, 0);
cmd_item.DisplayMember = "item_name";
cmd_item.ValueMember = "item_id";
cmd_item.DataSource = dt;
con.Close();

现在默认情况下,行组合中显示的值取决于网格数据源中该列的值。
因此,例如,如果网格中的一行的组合框所在的列的值为-1,则将显示条目“选择项”。

编辑
将新记录添加到gridview时,似乎想要ComboBox列的默认值。在这种情况下,Microsoft suggest使用事件 DefaultValuesNeeded 。在事件处理程序中,可以将单元格值设置为期望值,以显示选择项文本。

private void invoice_datagrid_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    // Set the default value for the combobox column in new rows.
    e.Row.Cells("combobox_column_key").Value = -1
}

在这里 combobox_column_key 应该用组合框替换为该列的键