tags:

views:

39

answers:

1

hi comunity!!! since method Add() takes Object as an argument, can I add for example datatables, then unbox them?

example:

cmbEmpresa.Items.Add(dt1);
cmbEmpresa.Items.Add(dt2);
cmbEmpresa.Items.Add(dt3);

then do something like:

datagrid.datasource=(DataTable)cmbEmpresa.SelectedItem;

EDIT:

and what about adding different type of objects, how can I unbox them according to the SelectItem's original type?

+2  A: 

Boxing and unboxing actually means changing a value type into an object and vice-versa, so that's probably not the right term for what you mean.

You can store any type of object you like in your ComboBox and cast back to the original type as needed.

Eric J.
what if I add different type of objects, for example a DataTable and a DataSet, how can I unbox them according to the object's original type??
Luiscencio
You can use the GetType method and typeof operator to figure out what the original type was and then cast accordingly, e.g. if (myObject.GetType() == typeof(string)) { // Cast to a string and use it. An alternative approach (especially if there are only a very small number of choices is to use the As operator, which casts an object to a specific type if it was already of that type, else returns null, e.g. string s = myObj as String; if (s != null) { // use it as a string
Eric J.
When using reflection to check if a cast is valid `.GetType() == typeof(blah)` will not deal with inheritance properly. For the equivalent to the `as` or `is` operators, look at the `Type.IsAssignableFrom` (http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx) method.
Nader Shirazie
That's a good point Nader, if members of an inheritance hierarchy are involved.
Eric J.