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

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.
 
M

Marina

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.
 
N

needin4mation

There is no myReader.Item in C# like in VB.NET that I can find. Maybe
it is called something else?
 
M

Marina

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.
 
N

needin4mation

Thanks I was able to do this:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top