如何将值添加到DataGridViewComboBoxColumn数据源
本文关键字:DataGridViewComboBoxColumn 数据源 添加 | 更新日期: 2023-09-27 18:07:01
我有一个问题,其中我在DataGridView
中有一个DataGridViewComboBoxColumn
,我想向DataSource
添加一个项目。
我最初将DataSource属性设置为List<string>
,它可以正常工作。稍后,我将在这个列表中添加一个项目,这很好。但是当我尝试在组合框中选择这个项目时,我得到一个数据验证错误,
系统。ArgumentException: DataGridViewComboBoxCell值无效。
此外,我不能实际地将组合框设置为新添加的值。
下面是一个完整的工作示例。
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);
}
}
如何为DataGridViewComboBoxColumn
添加DataSource
项目?
改变
button.Click += (e, s) => this.Data.Add("Thing3");
button.Click += (e, s) =>
{
col1.DataSource = null;
this.Data.Add("Thing3");
col1.DataSource = Data;
};