是否可以在循环的dataTable中为组合框添加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??
}
如果使用绑定到数据表的datagridview,则不会弄乱网格中的各个组合框。您可以执行以下操作(我将包含设置代码):
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`
这是将组合中的项目列表与主表中的数据连接起来的最后一行。当这样完成绑定时,我们根本不会理会任何组合的selctedIndex;该组合将显示与在基本行(sourceData.Gender
)中找到的1/2/3有关的“男性/女性/未指定”-通过在comboData.Valu
列中查找值1/2/3来执行此操作。设置新的性别时,它将从comboData.Valu
中取出相应的SelectedValue并将其存储回行中。您还有另一列绑定到sourceData.Gender
-在更改组合框中的设置时,它也会更改(可能必须导航到另一行)
现在只需确保将列添加到datagridview:
dataGridView1.Columns.Add(dgvcbcGender);