Reputation: 1276
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
Upvotes: 0
Views: 10961
Reputation: 12026
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.
Upvotes: 1
Reputation: 44931
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
Upvotes: 1