extracting integers from datarows

  • Thread starter Thread starter apandapion
  • Start date Start date
A

apandapion

I have an integer value inside a datarow. Is there a more graceful way
to extract it than this:

int value = Convert.ToInt32(datarow[datacolumn].ToString());

It's already an integer. Is there a way around the conversion?
 
Marc Gravell said:
Have you tried
int value = (int) datarow[datacolumn];
?
Marc

I had the same problem - doing the above, I got an invalid cast error, and
had to use the method the OP suggested (although I don't need to put the
"ToString()" on the end)
James
 
Hi,


I have an integer value inside a datarow. Is there a more graceful way
to extract it than this:

int value = Convert.ToInt32(datarow[datacolumn].ToString());

There is no need to convert it to string,
Convert.ToInt32(datarow[datacolumn] ); will be good.
 
Hi
I had the same problem - doing the above, I got an invalid cast error, and
had to use the method the OP suggested (although I don't need to put the
"ToString()" on the end)
James

I think I remember having such a problem too, I got used a long time ago to
always use Convert.ToXXX .
 
Ignacio said:
Hi



I think I remember having such a problem too, I got used a long time ago to
always use Convert.ToXXX .

I guess it makes a kind of sense - if you're pulling a dataset from a
web service, it comes as XML which is essentially a huge string.
 
james said:
I had the same problem - doing the above, I got an invalid cast error, and
had to use the method the OP suggested (although I don't need to put the
"ToString()" on the end)

The exception should have told you what the original type was (I think
- if not, it's easy enough to do).

Sometimes you need two casts, but I think that's generally nicer than
formatting and then parsing.
 
Hi,

I guess it makes a kind of sense - if you're pulling a dataset from a
web service, it comes as XML which is essentially a huge string.


Yes, but that's when it's serialized, as soon as it's created in memory as a
dataset instance (deserialized) it's not longer a long string. each column
will have the expected type.
 
HI Jon,
Sometimes you need two casts, but I think that's generally nicer than
formatting and then parsing.


Can you provide a case where you need two casting?
 
Can you provide a case where you need two casting?

Yup - if you want something as an int, but it's currently a boxed
SqlInt32. Basically you need one cast for the unboxing, and another for
the explicit conversion:

using System;
using System.Data.SqlTypes;

class Test
{
public static void Main()
{
object o = new SqlInt32(10);
int x = (int) (SqlInt32) o;
}
}

(There are other ways of doing it, of course, but the above is about as
simple as it gets, IMO.)
 
Back
Top