Using colum name to get data from a datareader in C#

  • Thread starter Thread starter Bjorn Sagbakken
  • Start date Start date
B

Bjorn Sagbakken

Well, that about the whole question.
I'm trying to convert from VB to C#, and so far I have figured out most of
the issues.
But I haven't found a way to retrieve the column data from a datareader
using the coumn name, only it's zero-based column ordinal (like
myDataReader.GetString(8) ... ) and when I use several sql joins, I don't
know the exact order of the colums in the result.

Any tip?

Bjorn
 
But I haven't found a way to retrieve the column data from a datareader
using the coumn name, only it's zero-based column ordinal (like
myDataReader.GetString(8) ... ) and when I use several sql joins, I don't
know the exact order of the colums in the result.

myDataReader.GetString(myDataReader.GetOrdinal("ColumnName"))
 
Well, that about the whole question.
I'm trying to convert from VB to C#, and so far I have figured out most of
the issues.
But I haven't found a way to retrieve the column data from a datareader
using the coumn name, only it's zero-based column ordinal (like
myDataReader.GetString(8) ... ) and when I use several sql joins, I don't
know the exact order of the colums in the result.

Any tip?

myDataReader.GetString(myDataReader.GetOrdinal["myColumn"]);
 
Muhammad Naveed Yaseen said:
myDataReader.GetString(myDataReader.GetOrdinal("ColumnName"))

Thanks. I actually found out myself a few minutes ago.

Bjorn
 
Mark Rae said:
Well, that about the whole question.
I'm trying to convert from VB to C#, and so far I have figured out most
of the issues.
But I haven't found a way to retrieve the column data from a datareader
using the coumn name, only it's zero-based column ordinal (like
myDataReader.GetString(8) ... ) and when I use several sql joins, I don't
know the exact order of the colums in the result.

Any tip?

myDataReader.GetString(myDataReader.GetOrdinal["myColumn"]);

Thanks. I actually found out myself a few minutes ago.

Bjorn
 
myDataReader.GetString(myDataReader.GetOrdinal["myColumn"]);

Thanks. I actually found out myself a few minutes ago.

Bjorn

Assuming the datareader is populated...

dataValue = dr["columnName'];

example:
while(dr.Read())
{
string name = dr["PURCH_ID"];
string addr = dr["ADDR"];
}
 
dataValue = dr["columnName'];

example:
while(dr.Read())
{
string name = dr["PURCH_ID"];
string addr = dr["ADDR"];
}

That won't compile because dr[...] is not strongly typed i.e. it returns an
object type. The above code will throw the following exception:
Cannot implicitly convert type 'object' to 'string'. An explicit conversion
exists (are you missing a cast?)

That's why the OP was using the GetString() method. If you don't want to use
that, you'll have to explicitly cast e.g.

string addr = Convert.ToString(dr["ADDR"]);

or

string addr = dr["ADDR"].ToString();
 
Back
Top