How do I find out if a column exists in a VB.Net DataRow

后端 未结 4 1015
暖寄归人
暖寄归人 2021-02-01 00:44

I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missin

4条回答
  •  日久生厌
    2021-02-01 01:25

    Another way to find out if a column exists is to check for Nothing the value returned from the Columns collection indexer when passing the column name to it:

    If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
        MsgBox("YAY")
    End If
    

    This approach might be preferred over the one that uses the Contains("ColumnName") method when the following code will subsequently need to get that DataColumn for further usage. For example, you may want to know which type has a value stored in the column:

    Dim column = DataRow.Table.Columns("ColumnName")
    If column IsNot Nothing Then
        Dim type = column.DataType
    End If
    

    In this case this approach saves you a call to the Contains("ColumnName") at the same time making your code a bit cleaner.

提交回复
热议问题