我需要基于以下两个类来设置DataGridView
public class Selection
{
public string Display { get; protected set; }
public int Value { get; protected set; }
public Selection( string d, int v)
{
Display = d; Value = v;
}
}
public class TestData
{
public Selection Selection { get; protected set; }
public int Quantity { get; protected set; }
public TestData( Selection sel, int q)
{
Selection = sel;
Quantity = q;
}
}
TestData对象是行。用户必须从由列表或类似内容填充的ComboBox列中选择一个Selection。 但是TestData集合必须是BindingList才能添加或删除行,因此,它是datagrid DataSource。 到目前为止,我正在尝试使用以下代码设置de grid
List<Selection> getSelectionList()
{
List<Selection> result = new List<Selection>();
result.Add(new Selection("Zero", 0));
result.Add(new Selection("One", 10));
result.Add(new Selection("Two", 20));
result.Add(new Selection("Three", 30));
result.Add(new Selection("Four", 40));
result.Add(new Selection("Five", 50));
result.Add(new Selection("Six", 60));
return result;
}
List<TestData> getTestDataList(List<Selection> reference)
{
List<TestData> result = new List<TestData>();
result.Add(new TestData(reference[1], 10));
return result;
}
................
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
List<Selection> list = getSelectionList();
combo.DataSource = list;
combo.DisplayMember = "Display";
combo.ValueMember = "Value";
BindingList<TestData> source = new BindingList<TestData>(getTestDataList(list)) { AllowEdit = true, AllowNew = true, AllowRemove = true };
dataGridView1.DataSource = source;
................
但是结果很烦人: a)网格显示两行(即使我在TestData列表中仅设置了一个元素) b)组合单元中没有数据。
我该如何解决?
TIA
答案 0 :(得分:0)
您只需要添加两行:
string key = ((KeyValuePair<string, string>)combo.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)combo.SelectedItem).Value;