【问题标题】:How do I add values to a DataGridViewComboBoxColumn DataSource?如何向 DataGridViewComboBoxColumn 数据源添加值?
【发布时间】: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 方法。我查看了ValueMemberDisplayMember,但我不知道如何设置它们。它们应该是我的对象的属性,但我的对象只是字符串。
  • @DJKRAZE DataBind 用于 ASP.Net

标签: c# .net datasource datagridviewcombobox


【解决方案1】:

变化

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

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

对我有用。

【讨论】:

  • 虽然这消除了消息,但它还有许多其他副作用。最重要的是,将DataSource 设置为null 会清除当前网格中每一行的值。其次,添加按钮现在添加了标题为“长度”的第二列。第三,网格现在似乎有问题。多次选择“Thing3”会导致 NRE。
  • 你正在设置col1的DataSource,对吧?它不应该影响每个数据网格的行。
  • Kris,我没有遇到你提到的任何副作用。我刚刚从问题正文中获取了您的测试代码,并按照 Jacob 的建议替换了 Click 处理程序......它工作正常,没有丢失的值,没有第二列,也没有 NRE......
猜你喜欢
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2016-10-26
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多