vb.net 验证数据表中是否存在列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32823164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:29:00  来源:igfitidea点击:

Verify if a column exist in a DataTable

vb.net

提问by Pietro Z.

I need to update an item in a DataTable only if a column exist.
I've tried to write this, but it doesn't work because the column "carta_sistemata" doesn't exist.

仅当存在列时,我才需要更新 DataTable 中的项目。
我试图写这个,但它不起作用,因为“carta_sistemata”列不存在。

If table.Rows(0).Item("column_name") IsNot Nothing Then
    TextBox.Text = table.Rows(0).Item("column_name").ToString
End If

Without the "if" the code works, but if the column doesn't exist it throws an exception.

如果没有“if”,代码可以工作,但如果该列不存在,则会引发异常。

TextBox.Text = table.Rows(0).Item("column_name").ToString

回答by codersl

Check column exists before accessing:

在访问之前检查列是否存在:

If table.Columns.Contains("column_name") Then
    TextBox.Text = table.Rows(0).Item("column_name").ToString
End If

回答by tezzo

You can use a Try/Catchblock:

您可以使用一个Try/Catch块:

Try
    Me.TextBox1.Text = YourDataTableTable.Rows(0).Item("ColumnName").ToString
Catch ex As Exception
End Try

回答by Andrew Mortimer

You can parse through the DataColumn collection on the table and look for the presence of the column you're interested in.

您可以解析表上的 DataColumn 集合并查找您感兴趣的列的存在。

   For Each col As DataColumn In table.Columns
       If col.ColumnName = "carta_sistemata" Then
             'do your update
             Exit For
       End If
   Next