繁体   English   中英

如何将值添加到DataGridViewComboBoxColumn数据源?

[英]How do I add values to a DataGridViewComboBoxColumn DataSource?

我有一个问题,其中我在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);
    }
}

如何将项目添加到DataGridViewComboBoxColumnDataSource中?

改变中

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

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

为我工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM