【问题标题】:Combo box is not displaying default value in DataGridView in C#组合框未在 C# 中的 DataGridView 中显示默认值
【发布时间】:2011-10-10 02:17:37
【问题描述】:

我试图让用户从DataGridViewComboBoxColumn 中为每个新行选择值。我已将GridView 中的ComboBox 绑定到数据库,但每当我输入新行时,我都会看到DataGridViewComboBoxColumn 没有初始值。我必须先设置值。

当我在DataGridView 中输入新行时,如何让默认值出现在DataGridViewComboBoxColumn 中?

这就是我将DataGridView ComboBox 绑定到数据库的方式:

bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1; 
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";

【问题讨论】:

    标签: c# winforms datagridview combobox


    【解决方案1】:

    您可以使用组合框列的DefaultCellStyle.NullValueDefaultCellStyle.DataSourceNullValue 属性。

    关于这个here有一篇相当全面的MSDN文章。

    我还在下面给出了一个代码示例:

    // Let's say I have this list of cars I want to add to my datagridview
    List<Car> cars = new List<Car>();
    cars.Add(new Car() { Index = 0, Make = "Ford" });
    cars.Add(new Car() { Index = 1, Make = "Chevvy" });
    cars.Add(new Car() { Index = 2, Make = "Toyota" });
    
    // I create the column, setting all the various properties
    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
    col.DataSource = cars;
    col.Name = "Cars";
    col.DisplayMember = "Make";
    col.HeaderText = "Car";
    col.ValueMember = "Index";
    col.DataPropertyName = "Car";
    
    // As well as standard properties for a combobox column I set these two:
    col.DefaultCellStyle.NullValue = cars[0].Make;
    col.DefaultCellStyle.DataSourceNullValue = cars[0].Index;
    
    dataGridView1.Columns.Add(col);
    
    dataGridView1.DataSource = dt;
    

    上面代码需要注意的一点是,我将DataPropertyName 设置为允许与datagridview 的数据源上的属性绑定。

    如果我没有这样做,那么当用户没有选择任何内容时,我需要在访问组合框列时添加一些额外的逻辑,因为属性的值将为空(NullValue 不会将值设置为实际值)单元格,仅显示默认值)。

    【讨论】:

      【解决方案2】:
      bindingSource1.DataSource = itemBAL.GetTable();
      dataGridView1.DataSource = bindingSource1; 
      ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
      ItemName.DisplayMember = "Name";
      ItemName.ValueMember = "ItemId";
      

      只添加这一行

      dataGridView1["ItemName",dataGridRowNumber].value=1;//item id value
      

      【讨论】:

        【解决方案3】:

        您可以在设计器或代码中将项目添加到您的DataGridViewComboBoxColumn

        【讨论】:

          猜你喜欢
          • 2011-10-11
          • 1970-01-01
          • 2014-02-14
          • 2014-12-13
          • 2013-08-05
          • 2017-11-30
          • 1970-01-01
          • 2011-11-21
          • 1970-01-01
          相关资源
          最近更新 更多