Search code examples
c#winformsdatagridviewdatagridviewcolumndatagridviewcomboboxcell

C# populate DataGridViewComboBoxCell from dataset and get the selected value from database


I need to add different values from database to my DataGridViewComboBoxColumn from Table 1(id,name,...) and must have selected value(name) it.

My code:

SqlDataAdapter coursead = new SqlDataAdapter("select * from tbl_armycourses", longrollcon);
coursead.Fill(courseds, "tbl_armycourses");

for (int j = 0; j < ds5.Tables[0].Rows.Count; j++)
{
    DataGridViewComboBoxCell ComboColumn = (DataGridViewComboBoxCell)(dataGridView5.Rows[j].Cells[0]);
    ComboColumn.DisplayMember = "course_name";
    ComboColumn.ValueMember = "armycourse_id";
    ComboColumn.DataSource = courseds.Tables["tbl_armycourses"];
}
for (int i = 0; i < ds5.Tables[0].Rows.Count; i++)
{
    int courseid = Convert.ToInt32(ds5.Tables[0].Rows[i]["course_id"]);
    dataGridView5.Rows.Add("..i want to add here selected index of comboboxcolumn..", ds5.Tables[0].Rows[i]["course_year"], ds5.Tables[0].Rows[i]["course_grading"], ds5.Tables[0].Rows[i]["course_auth"]);
}

Solution

  • If that ComboBoxColumn is added to your DataGridView as first column, then it's enough to add the value of cell and then it will display as selected in combobox:

    dataGridView5.Rows.Add(Convert.ToInt32(ds5.Tables[0].Rows[i]["course_id"]), 
                           ds5.Tables[0].Rows[i]["course_year"],
                           ds5.Tables[0].Rows[i]["course_grading"], 
                           ds5.Tables[0].Rows[i]["course_auth"]);
    

    Pay attention that the value should exist in combo box, otherwise you will receive exception.

    Also you should fill that combobox column this way, you don't need a loop:

    SqlDataAdapter coursead = new SqlDataAdapter("select * from tbl_armycourses", longrollcon);
    coursead.Fill(courseds, "tbl_armycourses");
    
    var ComboColumn= (DataGridViewComboBoxColumn)dataGridView5.Columns[0];
    ComboColumn.DisplayMember = "course_name";
    ComboColumn.ValueMember = "armycourse_id";
    ComboColumn.DataSource = courseds.Tables["tbl_armycourses"];
    

    Pay attention that the first column should be of type DataGridViewComboBoxColumn otherwise you will receive an exception.

    Note:
    In general, I recommend you to use data binding - for example to a DataTable - and don't add rows this way. One of the best features in Windows Forms is using Designer and using DataBinding.