views:

74

answers:

1

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 doing wrong?

Thanks

+1  A: 

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.

Preston
Preston, thanks for the feedback. That sorts out the DataSource for the enum which is great. I have similar problems with the IList<ResultInfo> though and would like to be able to display these through binding, but obviously the datasource varies for each row. Is there a way I can define this without doing it at runtime?
Ian
Are you trying to show the contents of the list as items in a combo box?If so, I can't think of a good design time solution. But you can do it at runtime. Each DataGridViewComboBoxCell in the column has its own DataSource property. So you would not set the DataPropertyName value on that column. Instead loop through the cells after the data has been bound and set the DataSouce on each cell to the list on the rows (Result)DataBoundItem. I guess you could then set the Value on the cell to the first item in the list or something.
Preston