我已经按照这个教程完成了:
http://www.timvw.be/2007/01/17/exploring-datagridviewcomboboxcolumn-databinding/
我只能概述一下:
有一个 TypeCode 代表 ComboBox-Values 的一种类型。
这是我的主要 BindingList XYZ 的连接点。 XYZ 是数据集,其中包含一个属性 TypeCode。您现在可以轻松地将此 XYZ 列表绑定到您的 dataGridView。重要的是为每列绑定PropertyName。
您应该做的一件事是在您的 Visual Studio Explorer 中定义列。您在 datagridview 中手动设置要包含数据的列。例如:用 textboxcolumn 定义列 value1,用 comboboxcolumn 定义 value2。
在您的代码中,您现在可以使用数据集 XYZ 引用该列:
this.valuetextboxcolumn.DataPropertyName = "value1";
现在您可以向数据集 XYZ 添加值。
最后用这个绑定它:
this.XYZ_Binding_Source.DataSource = XYZ;
this.dataGridView1.DataSource = this.XYZ_Source;
您还必须在代码中定义所有这些元素。
comboboxcolumn 的值现在可以通过这一行轻松更改:
XYZ.TypeCode = TypeCode.valuecode1;
您必须将另一个列表绑定到包含用户可以选择的类型的组合框。
this.DataGridViewComboBoxColumn.DataPropertyName = "TypeCode";
this.DataGridViewComboBoxColumn.DisplayMember = "Label";
this.DataGridViewComboBoxColumn.ValueMember = "TypeCode";
DataPropertyName 是 XYZ-List 中元素的 TypeCode 和绑定到组合框的每个元素的 TypeCode 的变量。如果您现在在组合框按钮上键入,您会看到绑定到组合框的每个元素的“标签”。包含组合框的值也是 TypeCode。
您现在可以像这样将几个列表项添加到组合框列表中:
bindingList.Add(new Type(LabelText, TypeCode.valuecode1));// only an example
正如您在 timvw 的教程中看到的,您必须使用此事件方法评估用户输入:
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (this.dataGridView1.CurrentCell.ColumnIndex == this.DataGridViewComboBoxColumn.Index)
{
BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;
XYZ xyz = bindingSource.Current as XYZ;
BindingList<Type> bindingList = this.add_all_data_sets_which_can_be_chosen();
DataGridViewComboBoxEditingControl comboBox = e.Control as DataGridViewComboBoxEditingControl;
comboBox.DataSource = bindingList;
if (xyz.TypeCode != null)
{
comboBox.SelectedValue = xyz.TypeCode;
}
else
{
comboBox.SelectedValue = string.Empty;
}
comboBox.SelectionChangeCommitted -= this.comboBox_SelectionChangeCommitted;
comboBox.SelectionChangeCommitted += this.comboBox_SelectionChangeCommitted;
}
}
void comboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
this.dataGridView1.EndEdit();
}
代码的简要说明:
如果用户单击组合框的一个数据集,则一个事件会出现,并且现在可以添加用户可以选择的每个数据集。 Combobox 的数据集是非常动态的。如果将所选数据集添加到 XYZ 列表的属性“类型代码”,则类型代码现在显示在组合框上。之后,dataGridView1 的 endedit() 方法会被自动调用。