views:

62

answers:

2

I created a class called CustomData which uses another one called CustomOptions as one of its fields. I want to use the CustomData in a DataTable as values. Here's a short overview (simplified, the fields are private and the accessors public, mostly readonly and the set is done by custom methods);

enum CustomDataOptionType
{
 // Some values, not important
}

class CustomOptions
{
 public CustomDataOptionType type { get; }
 public Dictionary<string, string> values { get; }
 // Some Methods to set the values
}

class CustomData
{
 public CustomOptions options { get; }
 // Some Methods to set the options
}

So, in the "actual" class that uses the ones above, I create a DataTable, using columns that are typeof(CustomData).

But when I try to access the columns, e.g. by

DataRow Row = data.Rows.Find("bla");
Row["colmn1"].options; // Not possible

Why can't I access the options-field?

+1  A: 

You need to cast it into the type CustomData.

((CustomData)Row["colmn1"]).options

o.k.w
+3  A: 

Because the Row["column1"] returns "object". You need cast the value to your type:

((CustomData)Row["column1"]).Options.

EDIT: If you want handle the NULL values, you should use this:

CustomData data = Row["column1"] as CustomData;
if ( null != data ) {
    // do what you want
}

Or you can use a extension methods for simplify it:

public static DataRowExtensionsMethods {
    public static void ForNotNull<T>( this DataRow row, string columnName, Action<T> action ) {
        object rowValue = row[columnName];
        if ( rowValue is T ) {
            action( (T)rowValue );
        }
    }
}
// somewhere else
Row.ForNotNull<CustomData>( "column1", cutomData => this.textBox1.Text = customData.Username );
TcKs
And when I do so, I'd have to make sure there is never anything else in the columns or is that done automatically due to `typeof(CustomData)`-definition of the columns?
ApoY2k
The code is assuming you are dead sure the type is the correct one at that column.
o.k.w
If set the DataType of colum to "typeof(CustomData)", then there can be only the "CustomData" and/or the "DBNull" which represents the "NULL" value.
TcKs
Well, I can be dead sure as I can catch any other (false) objects in the method that adds the `CustomOptions` to the `CustomData.options`-Field, can't I?
ApoY2k
@ApoY2k: If you can ensure that and/or do like what TcKs mentioned, you are pretty safe :)
o.k.w