Koby Douek
Koby Douek

Reputation: 16675

Getting int value from DataRow without converting to string

I have a database field as int. When I try this:

int val = Convert.ToInt32(row["Int_Field_Name"].ToString());

it works.

But this looks very bad and ineffective.

I tried these:

int val = row.Field<int>("Int_Field_Name");
int val = (int)row["Int_Field_Name"];

But they throw an exception: Specified cast is not valid

Is there a more elegant and more effective way ?

Upvotes: 3

Views: 11890

Answers (2)

Zolt&#225;n Tam&#225;si
Zolt&#225;n Tam&#225;si

Reputation: 12764

The problem is that most of ADO classes like DataTable are weakly-typed, so all you can directly extract from them is object. The reason is that the underlying providers decide what the data type will be. For example when your underlying data is coming from some database, what you expect to be an int, can actually be a short, uint, ulong or long, or even DBNull.Value value. Hence you need using the Convert.To* method family to be completely safe.

But one thing you don't have to do in most cases is calling ToString. The conversion functions will nicely convert the values if they are convertible. By convertible I mean they will fail for example if you try to convert a long value larger than int.MaxValue to int.

So your best bet is using

Convert.ToInt32(row["Int_Field_Name"])

If you feel this ugly (I do a bit too), you can introduce extension methods, like

public static int GetInt(this DataRow row, string fieldName) {
    return Convert.ToInt32(row[fieldName]);
}

and use it like myRow.GetInt("Int_Field_Name"). Of course you can make this extension more robust by some checks and possibly with a fallback value, etc.

Upvotes: 9

Kula
Kula

Reputation: 25

Try :

 int q = Convert.ToInt32(row["Int_Field_Name"]);

there is also ToInt16 and 64, depend what you need

Upvotes: 2

Related Questions