3

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"]);
}
Tobbe
  • 1,825
  • 3
  • 21
  • 37
Manraj
  • 496
  • 2
  • 15
  • If you add the Value if the Item you want selected as the Cell Value it will be selected. Is that what you want? – TaW Oct 29 '15 at 11:47
  • yes first populate that column from dataset and then set the selected value from databse – Manraj Oct 29 '15 at 12:01

1 Answers1

1

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398