Question: DataReader GetValue

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

Is it possible to get the value of a field (in a datareader) based on the
column NAME, rather than position? Right now I'm accessing it like this:

drMyDataReader.GetValue(16).ToString

It's a real pain, especially if I have to add a field or two. I have to
then RENUMBER all my existing code.

Please help. Thanks!
 
Yes, something like (in VB):

myDataReader("myColName") will work. You basically index by column name.
 
When I use the column name it gives me this error:

"Optional Strict On disallows implicit conversions from 'String' to
'Integer'."

From this it seems that it has to be an index or integer. Any ideas?
 
This returns an object - so you have to explicitly cast it or convert it to
the correct data type.

If you are going to use column names, you will have to deal with objects,
and convert them as needed to whatever you need.
 
Yes, it will. Let me recommend against using a Column name... it can
seriously hinder performance. If you need to use a readable name, there's a
..GetOrdinal method of the datareader so you can use an integer and name it
something clear.

Dim myClearName as Integer = myDataReader.GetOrdinal("myColumnName") then
you can use the myClearName in the DataReader.Read and have the best of both
worlds.

Is this the line that's barking at you? It so, there's definitely not any
conversion if you use GetOrdinal.

I think the getvalue may be the problem though....

you should be able to use something like

myArrayList.Add(myDataReader.GetString(ColumnIndexViaGetOrdinal) or GetInt.
Also make sure that you don't have DBNull or are testing for them in advance
b/c if you don't, you can't convert DBNull to a string and you'll raise an
exception.

MOST IMPORTANTLY, Don't turn off option strict. If the above doesn't fix
the problem, post the whole line giving you the problem and we can get it
fixed for you.

HTH,

Bill
 
I don't recommend use of the column name as it's so much more expensive
(performance-wise). You can setup enumerations that resolve to the column
ordinal which should resolve faster than referencing the GetOrdinal method.

hth

--
____________________________________
Bill Vaughn
MVP, hRD
www.betav.com
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
__________________________________
 
Back
Top