Set default value in DataGridView combo box

14,383

The answer to your other post should be helpful: Combo box is not displaying default value in DataGridView in C#

See the comment at the end of the first answer. Setting a null value only displays a default value but doesn't actually set it.

Share:
14,383

Related videos on Youtube

Cassie
Author by

Cassie

Updated on June 04, 2022

Comments

  • Cassie
    Cassie almost 2 years

    I'm using DataGridView in windows form to allow the user to add n numbers of rows with values enter by the user. One of the column of DataGridView contains combo box, which is displaying its items by using database.

    I'm using the following code in Load event to connect DataGridViewComboBox with database :

    private void PurchaseMaster_Load(object sender, EventArgs e)
    {
        DataTable dt = itemBAL.GetTable();
        bindingSource1.DataSource = dt;
        ItemName.DataSource = bindingSource1;
        ItemName.DisplayMember = "Name";
        ItemName.ValueMember = "ItemId";
        ItemName.DataPropertyName = "ItemId";
        ItemName.AutoComplete = true;
        ItemName.DefaultCellStyle.NullValue = dt.Rows[0][1].ToString();
        ItemName.DefaultCellStyle.DataSourceNullValue = dt.Rows[0][0].ToString();
    }
    

    But whenever I not select any value from DataGridViewComboBox and click on save button I find null value in the table corresponding to DataGridViewComboBox value.

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow)
            continue;
    
        DataRow dtRow = dt.NewRow();
        for (int i = 0; i < dataGridView1.Columns.Count; i++)
            dtRow[i] = row.Cells[i].Value == null ? DBNull.Value : row.Cell[i].Value;
        dt.Rows.Add(dtRow);
    }
    

    Could anyone please tell me why I'm getting null value in database for DataGridViewcombobox defult value, despite of using DataSourceNullValue property?