Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get single value from a datatable

Status
Not open for further replies.

jen89

Programmer
Aug 16, 2001
105
US
Hi,

I am trying to write a generic sub in VB to get a single (cell? field?) from a datatable. This function will be used in several apps. Here is my latest attempt:

Code:
    Sub GetGridField(ByVal pGrid As DataTable, ByVal nRow As Integer, ByVal nCol As Integer, ByVal pValue As String)

        Dim myRow As DataRow = pGrid.Rows(nRow)
        Dim myCol As DataColumn = pGrid.Columns(nCol)
        pValue = myRow(myCol)
        pValue = LTrim(pValue)

    End Sub

I have looked for code examples, but I think I must have a basic misunderstanding of how these things work, because I can't seem to apply them to my problem. Mostly, I see examples that iterate through the entire table like this:

Code:
Private Sub ColumnsDemo (ByVal myTable As DataTable)
   Dim myRow As DataRow, myColumn As DataColumn
   For Each myRow in myTable.Rows
      For Each myColumn In myTable.Columns
         Response.Write (myRow (myColumn))
      Next
   Next
End Sub

I understand the concept here, but I am having trouble determining how to specify the column and row index without a "for each" loop. The error my code above gives is "Cast from type 'DBNull' to type 'String' is not valid." I assume this means that whatever is being returned is coming out as null, since all the fields in my data table have a string in them. I'd appreciate any insight on this. A specific code example for these two lines would be helpful:
Code:
Dim myRow As DataRow = pGrid.Rows(nRow)
Dim myCol As DataColumn = pGrid.Columns(nCol)
They are the ones that I can't seem to translate from examples. Thanks!
 
nevermind, the code was right, but I mistakenly left an extra column in my datatable, throwing off the row index and - SURPRISE!!! - returning a null
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top