是否可以在循环中的dataTable中为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??
}
发布于 2020-03-24 01:21:10
如果您使用的是绑定到datatable的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);
https://stackoverflow.com/questions/60814401
复制相似问题