开发者

Databinding to the DataGridView (Enums + Collections)

I'm after a little help with the techniques to use for Databinding. It's been quite a while since I used any proper data binding and want to try and do something with the DataGridView. I'm trying to configure as much as possible so that I can simply designed the DatagridView through the form editor, and then use a custom class that exposes all my information.

The sort of information I've got is as follows:

public class Result
{
   public String Name { get; set; }
   public Boolean PK { get; set; }
   public MyEnum EnumValue { get; set; }
   public IList<ResultInfos> { get; set; }
}

public class ResultInfos { get; set; }
{
   public class Name { get; set; }
   public Int Value { get; set; }
   public override String ToString() { return Name + " : " Value.ToString(); }
}

I can bind to the simple information without any problem. I want to bind to the EnumValue with a DataGridViewComboBoxColumn, but when I set the DataPropertyName I get exceptions saying the enum values aren't valid.

Then comes the ResultInfo collection. Currently I can't figure out how to bind to this and display my items, again really I want this to be a combobox, where the 1st Item is selected. Anyone any suggestions on what I'm doin开发者_JS百科g wrong?

Thanks


Before you bind your data to the grid, first set the DataGridViewComboBoxColumn.DataSource like this...

combo.DataSource = Enum.GetValues(typeof(YourEnum));

I generally do this in the constructor after InitializeComponent(). Once this is set up you will not get an exception from the combo column when you bind your data. You can set DataGridViewComboBoxColumn.DataPropertyName at design time as normal.

The reason you get an exception when binding without this step is that the cell tries to select the value from the list that matches the value on the item. Since there are no values in the list... it throws an exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜