Get field value from a SQL data reader using VB.NET

Function: Get the field values based on passed sqldatareader and field name or position in Visual Basic .NET
Description:
An example function that checks if the parameter is a field name or field ordinal and then reads the field value from a data reader. The function will return a value if the field name or ordinal is existing and the value is not NULL but will return nothing if parameters are incorrect.

Function GetFieldValue(ByVal dbReader As SqlDataReader, ByVal Fieldnameid As Object) As Object

Try
Dim iFieldOrdinal As Integer
If TypeOf Fieldnameid Is String Then
iFieldOrdinal = dbReader.GetOrdinal(Fieldnameid)
Else
iFieldOrdinal = Fieldnameid
End If

If dbReader.IsDBNull(iFieldOrdinal) = False Then
GetFieldValue = dbReader.GetValue(iFieldOrdinal)
Else
GetFieldValue = Nothing
End If
Catch ex As SqlException
GetFieldValue = Nothing
MessageBox.Show(ex.ToString)
End Try
End Function

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>