Reputation: 24103
I am trying to add Combo box to datagridview and bind the combo with data and value. This is what I am doing and I ends up with many exceptions. What am I doing wrong?
IList<string> houseNums= myTable.Select(x => house_num).ToList();
dealersGridView.Columns.Clear();
dealersGridView.DataSource = myTable;
dealersGridView.Columns["id"].DisplayIndex = 1;
dealersGridView.Columns["id"].HeaderText = "Field 1";
dealersGridView.Columns["name"].DisplayIndex = 2;
dealersGridView.Columns["name"].HeaderText = "Field 1";
dealersGridView.Columns.Remove("house_num");
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Items.AddRange(new object[] { 1, 2, 3, 4, 5, 6, 7 });
column.DisplayIndex = 8;
column.HeaderText = "MyHeader";
column.DataSource = houseNums;
dealersGridView.Columns.Add(column);
The combo data doesn't bind and I don't see the selected values. What is wrong?..
Upvotes: 1
Views: 624
Reputation: 6890
I think that one of your problems is that you are adding values to the Items collection:
column.Items.AddRange(new object[] { 1, 2, 3, 4, 5, 6, 7 });
and then you are again setting the DataSource
property
column.DataSource = houseNums;
you need to do one or the other not both.
foreach (string e in houseNums) column.Items.Add(e);
or:
column.DataSource = myTable.Select(x => house_num).ToList();
Here's an article and an example hot to populate DataGridViewComboBoxColumn from a List<T>
.
One more thing. I noticed that you are selecting in a list from a table. I assume that this is a database table. You could bind a specific field from that table to the DataSource property.
Upvotes: 2