数据表 - 组合框中的 SelectedIndex

Datatable - SelectedIndex in Combobox

是否可以在循环中为数据表中的组合框添加 selectedIndex?

 DataGridViewComboboxColumn dataGrid = new DataGridViewComboboxColumn();
 datagrid.Datasource = enumData; //this works 
 datagrid.Name = "cmb"

 Datatable dt = new DataTable();
 dt.Columns.Add("cmb");
 for(int i = 0, i<200, i++)
 {
    var data = GetData(i);
    DataRow r =new DataRow();
    r["cmb] = data.value; //selectedIndex??

 }

如果您使用的是绑定到数据的数据网格视图table,则不会弄乱网格中的各个组合框。你做这样的事情(我将包括设置代码):

DataTable sourceData = new DataTable();
sourceData.Columns.Add("Name");
sourceData.Columns.Add("Gender", typeof(int));

sourceData.Rows.Add("John", 1);
sourceData.Rows.Add("Jane", 2);
sourceData.Rows.Add("Xxxx", 3);


DataTable comboData = new DataTable();
comboData.Columns.Add("Disp");
comboData.Columns.Add("Valu", typeof(int));


comboData.Rows.Add("Male", 1);
comboData.Rows.Add("Female", 2);
comboData.Rows.Add("Unspecified", 3);

现在了解具体细节:

dataGridView1 = new DataGridView();
dataGridView1.DataSource = sourceData;

//binding the dgv will create a couple of textbox columns, 
//now let's add a combo column to demo the binding concept


DataGridViewComboboxColumn dgvcbcGender = new DataGridViewComboboxColumn();
dgvcbcGender.Datasource = comboData; //refers to the male/female/unspecified table
dgvcbcGender.DisplayMember = "Disp"; //show john/jane/Xxxx in the combo
dgvcbcGender.ValueMember = "Valu"; //use the 1/2/3 ints as values to be stored in the sourceData table
dgvcbcGender.DataPropertyName = "Gender"; //critical! == "read the `Gender` int value of the row in `sourceData`, look it up in the `Valu` column of `comboData`

它是连接组合中的项目列表与主 table 中的数据的最后一行。像这样完成绑定后,我们根本不会弄乱任何组合的 selctedIndex;该组合将显示与它在基行 (sourceData.Gender) 中找到的 1/2/3 相关的 Male/Female/Unspecified - 它通过在 [=14] 中查找值 1/2/3 来实现=] 列。当您设置新的 Gender 时,它会从 comboData.Valu 中取出相应的 SelectedValue 并将其存储回行中。您将另一列绑定到 sourceData.Gender - 当您更改组合框中的设置时,它也会发生变化(可能必须导航到另一行)

现在只需确保将列添加到数据网格视图:

dataGridView1.Columns.Add(dgvcbcGender);