如何将值添加到DataGridViewComboBoxColumn DataSource?

时间:2013-04-01 20:58:03

标签: c# .net datasource datagridviewcombobox

我遇到一个问题,我在DataGridViewComboBoxColumn中有一个DataGridView,我想在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);
    }
}

如何为DataSource的<{1}}添加项目?

1 个答案:

答案 0 :(得分:1)

更改

button.Click += (e, s) => this.Data.Add("Thing3");

           button.Click += (e, s) =>
           {
                col1.DataSource = null;
                this.Data.Add("Thing3");
                col1.DataSource = Data;
           };

对我有用。

相关问题