SqlDataReader Get Value By Column Name (Not Ordinal Number)

user9927 picture user9927 · Feb 4, 2015 · Viewed 60k times · Source

Using the methods of the SqlDataReader, I can get the value of a column by passing in it's ordinal, such as the value of the first column if I pass in read.GetValue(0), or the second column if I pass in read.GetValue(1).

In looking at the methods, I don't see an option to get the value of a column by passing in the name of a column, such as ColumnID. In my mythical example, I would want to pass in read.GetValueofColumn("ColumnID") and read the value in the column (note that the method GetValueofColumn doesn't exist so far as I can tell from the method list).

Am I missing the method to do this, or a way to do this?

Answer

MatthewG picture MatthewG · Feb 4, 2015

You can get the ordinal of the column by using the GetOrdinal method, so your call could be:

read.GetValue(read.GetOrdinal("ColumnID"));