Is there a way to get a column by name instead of ordinal?

  • Thread starter Thread starter needin4mation
  • Start date Start date
N

needin4mation

Hi, using C#, I have to do this to get the database columns in a
reader. Can it be done in one step?:


OdbcCommand command = new OdbcCommand(sqlSelectPersonal, conn);
OdbcDataReader PerReader = command.ExecuteReader();

while (PerReader.Read())
{
int address_id = PerReader.GetOrdinal("address_id");
int picture_id = PerReader.GetOrdinal("picture_id");
int last_name = PerReader.GetOrdinal("last_name");
int first_name = PerReader.GetOrdinal("first_name");
int middle_name = PerReader.GetOrdinal("middle_name");

txtLastName.Text = PerReader.GetString(last_name).ToString();
txtFirstName.Text = PerReader.GetString(first_name).ToString();
txtMiddleName.Text = PerReader.GetString(middle_name).ToString();
//GetInt32 because it is a number
txtAddressID.Text = PerReader.GetInt32(address_id).ToString();
}

In VB.NET I did it all in one step like this:

While myReader.Read()
if not IsDBNull(myReader.Item("prodNumber")) then
txtProduct.text = myReader.Item("prodNumber")
end if


Also, do you know how to do the IsDBNull test in C# like this VB.NET
above? Thank you for your time.
 
If you can index by name in VB, you can index by name in C# too. It is the
exact same class you are using.

You can check if an object equals to DBNull.Value, which is the equivalent
of calling the IsDBNull function.
 
There is no myReader.Item in C# like in VB.NET that I can find. Maybe
it is called something else?
 
You can index directly into it:

myReader["myCol"]

In VB this would be:

myReader("myCol")

The Item thing is because VB doesn't support indexers in the same way as C#.
So they defined a default property named Item. But in C# you have the
concept of an indexer.
 
Thanks I was able to do this:

txtLastName.Text = (string)PerReader["last_name"];
 
Back
Top