Access a class' property with a string literal?

S

Steve

I'm in a weird situation where I'm using ComboBox's in a DataGrid. When the
ComboBox selection changes, I'm currently storing the SelectedValue object
into the DataSource of the DataGrid cell. This is not what I want.
I want to bind a string to the datagrid, then bind the string and value of a
lookup table to the combo box. When the combobox lookup is changed, I
wanted to store the value in a different, unbound property of the bound
class.

Does that make sense? Anyway, in the constructor for the Derived
DataGridComboBoxColumn class, I pass in the 2 columns of a DataTable that
will represent the Display and Value fields for the control. I also wanted
to pass in the string name of the class property that I would like to update
with the value from the combo box. Then, when I update the grid, I can use
the CurrencyManager to get to the bound data and hopefully find the property
from the string name and set it's data?
The reason I can't just hard code this is that there are several combo
columns and they all need to access different fields of the bound class.

God, does that sound like a horrible hack :(

But, it's all I got...

Thanks for any help,
Steve
 
Y

yotaxp

Hey Steve,

So you want to set a value to the property of a class instance, but
the program only has the name of the member (property)... this looks
like a job for System.Reflection! Take a look in the MSDN library, and
see what helpful information it gives about the following functions:

System.Type myType = typeof(TypeOfClassToBeModified); // This doesn't
even have to be a type literal.
System.Reflection.PropertyInfo myProp =
myType.GetProperty(PropertyName);
myProp.SetValue(InstanceToBeModified, NewValue, null);
// The third paramiter is a list of paramiters to pass to indexed
properties. Use 'null' if it's not indexed.

Of course, there's that always-pleasing-to-look-at one-liner:

typeof(TypeOfClassToBeModified).GetProperty(PropertyName).SetValue(InstanceToBeModified,
NewValue, null);

Hope this helps!
"Yota"
 
S

Steve

I had read a reply from someone on tis thread and it worked perfect, it
involved reflection and had code samples and everything. Anyway, whoever
you are, sorry I can't find the original post from you but thanks for the
help, it worked awesome and it was cool to learn about the reflection stuff!
 

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