DataGridViewComboBoxColumn Data Binding Fun

Z

zaffle

Ok, lets see if I can phrase my question so that it makes sense to me,
and maybe even anyone else who reads this.....

I'll use the standard "Widget" explaination to explain what I'm trying
to do.

I have a DataGridView... thats a good start.
The DataGridView.DataSource is a BindingList<Widget>
Good start.. For the most part it works.

One of the Widget's properties is "Style", which is of the type
WidgetStyle.

I have another BindingList, WidgetStyles, which derived from
BindingList<WidgetStyle>.
It looks like this:
WidgetStyles styles = new WidgetStyles();
styles.Add(new WidgetStyle("Style A","Chrome","Round");
styles.Add(new WidgetStyle("Style B","Brass","Cube");
....etc..



I want the Style column in the DataGridView to be a ComboBox, offering
a list of the WidgetStyle's.

For various reasons, when I create the Style column, I do it as so:
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "Style";
col.DataSource = styles;
col.DataPropertyName = "Style";

Now, what I want is for the ValueMember of the column to actually be
the item, not a property of it...

I could do this by having the Widget class store the WidgetStyle as a
string, and do a lookup. Then the combobox column has the ValueMember
set to "Name" and all is well.

But I am difficult, and I want the Widget class to contain a property
named Style which is of the type WidgetStyle....

Can this be done?

I really hope this is understandable.. If needed I can create a quick
simple project that implements this and upload it somewhere if needed.

Nick
 
Z

zaffle

Ok, I solved my own problem.
I hadn't set DataGridViewComboBoxColumn.DisplayMember,
So the Combo box was behind-the-scenes coverting each item to a String,
then once the item was selected, it tried to convert it back.

So what I set is:
col.DataSource = styles;
col.DataPropertyName = "Style";
col.DisplayMember = "Name";

With ValueMember not set, it seems to pass the whole object back as the
value, which is what I want... Finally! Yey!

Nick
 
Z

zaffle

Ok, I solved my own problem.
I hadn't set DataGridViewComboBoxColumn.DisplayMember,
So the Combo box was behind-the-scenes coverting each item to a String,
then once the item was selected, it tried to convert it back.

So what I set is:
col.DataSource = styles;
col.DataPropertyName = "Style";
col.DisplayMember = "Name";

With ValueMember not set, it seems to pass the whole object back as the
value, which is what I want... Finally! Yey!
Nope, to reply to myself again, that statement doesn't appear to be
true.
I got around it by creating a property named "This", which is readonly
and returns this
get
WidgetStyle This { get { return this; } }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top