[英]How do I add values to a DataGridViewComboBoxColumn DataSource?
I have an issue wherein I have a DataGridViewComboBoxColumn
in a DataGridView
and I want to add an item to the DataSource
. 我有一个问题,其中我在
DataGridViewComboBoxColumn
中有一个DataGridView
,我想向DataSource
添加一个项。
I've initially set the DataSource property to a List<string>
which works fine. 我最初已将DataSource属性设置为
List<string>
,它可以正常工作。 Later I'll add an item to this list, which works fine. 稍后,我将一个项目添加到此列表中,效果很好。 But when I try to choose this item in a combobox, I get a data validation error,
但是,当我尝试在组合框中选择此项时,出现数据验证错误,
System.ArgumentException: DataGridViewComboBoxCell value is not valid.
System.ArgumentException:DataGridViewComboBoxCell值无效。
Further, I can't actually set the combobox to the newly added value. 此外,我实际上无法将组合框设置为新添加的值。
Here is a fully working example. 这是一个完整的示例。
public partial class Form1 : Form
{
List<string> Data { get; set; }
public Form1()
{
InitializeComponent();
// Populate our data source
this.Data = new List<string> { "Thing1", "Thing2" };
// Set up controls
var gvData = new System.Windows.Forms.DataGridView();
var col1 = new System.Windows.Forms.DataGridViewComboBoxColumn();
var button = new System.Windows.Forms.Button();
gvData.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { col1 });
// Set the column's DataSource
col1.DataSource = this.Data;
col1.HeaderText = "Test";
col1.Name = "col1";
// Set up a button which adds something to the source
button.Text = "Add";
button.Location = new System.Drawing.Point(0, 200);
button.Click += (e, s) => this.Data.Add("Thing3");
this.Controls.Add(gvData);
this.Controls.Add(button);
}
}
How can I add items to the DataSource
for my DataGridViewComboBoxColumn
? 如何将项目添加到
DataGridViewComboBoxColumn
的DataSource
中?
Changing 改变中
button.Click += (e, s) => this.Data.Add("Thing3");
to 至
button.Click += (e, s) =>
{
col1.DataSource = null;
this.Data.Add("Thing3");
col1.DataSource = Data;
};
has worked for me. 为我工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.