0

I have a

public object DataSource {get;set} and a public string DisplayMember {get;set}

The object can take everything like an IList or a CustomerListDataSet.

I do not know what the user will set in the DataSource.

I tried this

Type myType = DataSource.GetType().UnderlyingSystemType;

??? myUnknownObjectInstance = (mytype)DataSource;

I guess it is not possible even with Reflection access a myUnknownObjectInstance.PropertyNameFromDisplayMember and assign it a value like "Peter" ?

Beny
  • 11
  • 1
  • 1

3 Answers3

0

Could you refactor the class to use generics? so that you have a datasource of the generic type?

Mike Miller
  • 16,195
  • 1
  • 20
  • 27
0

You can determine your type explicitely by a

if (DataSource is IList)
{
 ...
}
else if (DataSource is DataTable)
{
...
}

etc

But if DataSource is not generic, there is no way you can do that cast like you specified. You can cast it, when it type is specified as a parameter.

You can access property by writing

PropertyInfo pi = DataSource.GetType().GetProperty(DisplayMember);
pi.SetValue(DataSource, "Peter");
Nickolodeon
  • 2,848
  • 3
  • 23
  • 38
0

I think you just need DataSource.GetType()

Homam
  • 23,263
  • 32
  • 111
  • 187