簡體   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