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.