0

Fairly new to .Net here and having trouble with a line of code. I have a routine in a custom class that is assigning values to an object based on data from a table row. However, several tables may be used to update these values and only have some of the fields in common. Therefore, I want to check each field value to make sure it exists before I attempt to access it's value to assign to my object. However, I am getting the error "Column x Does Not Belong To Table." Any suggestions as to how I might be able to accomplish this without throwing an error?

        'error occurs on first line
        If Not memberRow.Item("nickname") Is Nothing Then
            returnval.NickName = Trim(memberRow.Item("nickname").ToString)
        End If
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Carl
  • 1,246
  • 3
  • 21
  • 39

2 Answers2

1

If the column doesn't exist, the Item method will throw an exception.

Probably the easiest solution is:

Dim wIndex As Integer

wIndex = memberRow.Table.Columns.IndexOf("nickname")
If wIndex <> -1 Then
   returnval.NickName = Trim(memberRow.Item(wIndex).ToString)
Else
   returnval.NickName = String.Empty
End IF
competent_tech
  • 44,465
  • 11
  • 90
  • 113
  • This doesn't work because I am using a DataRow and not a DataSet and there doesn't appear to be an equivalent property of a DataRow to check in this manner. – Carl Dec 09 '11 at 19:23
  • Sorry, had a slight typo in the answer: it should be memberRow.Table not .Tables. – competent_tech Dec 09 '11 at 19:27
  • FYI - what I actually did was take the original format and changed it to If memberRow.Table.Columns.IndexOf("nickname") <> -1 Then – Carl Dec 09 '11 at 20:13
1

Assuming memberRow is of type System.Data.DataRow you will want to look at the table definition. Something like :

If ( memberRow.Table.Columns.Contains("nickname")) Then
   If Not memberRow.Item("nickname") Is Nothing Then
            returnval.NickName = Trim(memberRow.Item("nickname").ToString)
        End If
End If

You can also do as @competent_tech suggests and trap for exceptions, but that depends on which side of the slow/not-slow exception debate you fall on.

Community
  • 1
  • 1
EBarr
  • 11,826
  • 7
  • 63
  • 85