机会单元到组合框的属性

时间:2014-08-14 09:10:24

标签: c# datagridview combobox attributes

我使用dataGridView.DataSource = myList;填充dataGridView。

我使用以下代码隐藏类成员:

 [System.ComponentModel.Browsable(false)]
 public string SomeInformation { get; set; }

但是,还有一种方法可以说类成员应该表示为ComboBox吗?

如果没有,有什么方法可以用代码更改它吗?我尝试了以下方法:

DataGridViewComboBoxCell comboBoxCell = new DataGridViewComboBoxCell();
comboBoxCell.DataSource = State.Instance.ProductCategories.ToList();
dataGridView[2, 0] = comboBoxCell;
dataGridView[2, 0].Value = State.Instance.ProductCategories.ToList()[0];

该字段的值很好,但仍然没有ComboBox。

任何帮助?

修改

我现在使用以下代码:

 dataGridView.DataSource = State.Instance.Products;
 dataGridView.DataError += delegate(object o, DataGridViewDataErrorEventArgs args)
 {
     MessageBox.Show(args.Exception.Message);
 };

 DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
 col.DataPropertyName = "Categorie";
 col.Name = "Categorie";
 col.Visible = true;
 col.HeaderText = "Categorie";
 col.DataSource = State.Instance.ProductCategories.ToList();
 col.DisplayMember = "Name";
 col.DisplayIndex = 1;

 dataGridView.Columns.Add(col);

 dataGridView.CellEndEdit += delegate(object o, DataGridViewCellEventArgs args)
 {
     State.Instance.Save();
     // If I check the value here, it is a string.
 };

但是当我保存状态时,值不会被更改。可能是因为我自己添加了这个列而且它不知道在哪里保存它?

    [System.ComponentModel.Browsable(false)]
    public ProductCategory Categorie { get; set; }

在CellEndEdit事件中,我只返回字符串,但不是整个对象。

2 个答案:

答案 0 :(得分:1)

您可以设置 DataGridView.AutoGenerateColumns = false ,然后在代码中添加所有列,或自动生成列,然后添加自定义列(更改DisplayIndex以设置其位置):

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataPropertyName = "SomeInformation";
col.Name = "colSomeInformation";
col.Visible = true;
col.HeaderText = "Some Information"
col.DataSource = State.Instance.ProductCategories.ToList();
// set other column properties here...

dataGridView.Columns.Add(col);

我曾经不得不根据外部设置自动生成不同类型的datagridview列,我使用了xml配置文件。据我所知,没有内置的解决方案可以做到这一点。

修改

ValueMember如何运作:

class ProductCategory
{
  public int ID {get;set;}
  public string Name {get;set;}
}

class Product
{
   public int ID {get;set;}
   public string Name {get;set;}
   public int CategoryID {get;set;}
}


// Example data binding:

BindingList<Products> bl = new BindingList<Products>(State.Instance.Products.ToList());
BindingSource bs = new BindingSource();
bs.DataSource=bl;

dataGridView.DataSource = bs;

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = State.Instance.Categories.ToList();
col.DataPropertyName = "CategoryID";
col.DisplayMember= "Name"; // name of category
col.ValueMember ="ID"; // id of category

答案 1 :(得分:0)

我很确定这是不可能的。