【发布时间】:2013-03-23 00:27:45
【问题描述】:
我有一个问题,我在DataGridView 中有一个DataGridViewComboBoxColumn,我想向DataSource 添加一个项目。
我最初将 DataSource 属性设置为 List<string>,它工作正常。稍后我将在此列表中添加一个项目,它工作正常。但是当我尝试在组合框中选择此项目时,我收到数据验证错误,
System.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?
【问题讨论】:
-
你在哪里 / 调用 DataBind() 方法..?我也相信你需要分配 Combobox 的
ValueMember and DisplayMember只是快速浏览一下 -
@DJKRAZE 我没有设置它们,因为我读到了
string值,这无关紧要。我现在就试试。我不知道DataBind。在 WinForms 中设置数据源时,我从未使用过该方法。 -
DataBind() 通常在 DataGridview 中使用,但我只是注意到与实际组合框有关的其他一些事情,这就是我提到它的原因
-
DataGridView 似乎没有
DataBind方法。我查看了ValueMember和DisplayMember,但我不知道如何设置它们。它们应该是我的对象的属性,但我的对象只是字符串。 -
@DJKRAZE DataBind 用于 ASP.Net
标签: c# .net datasource datagridviewcombobox