Reputation: 82
My windows form application having Datagridview with combobox I need to set the first value for example ("Select item")
My result
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();
Upvotes: 2
Views: 1434
Reputation: 216243
First you need to add an entry in your database for the select item text
....
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();
Now the value displayed by default in the combo for your rows depends on the value for that column in the datasource of your grid.
So, for example, if a row in your grid has the value -1 for the column where you have the ComboBox then the entry "select item" will be showed.
EDIT
It seems that you want a default value for your ComboBox column when you add a new record to the gridview. In this case Microsoft suggest to use the event DefaultValuesNeeded. In the event handler you can set the cell value to the desidered value to show the select item text.
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
}
Here combobox_column_key should be replaced by the key for the column with the combobox
Upvotes: 2