如何判断DataRow中是否存在某列?
我正在将 XML 文件读入 DataSet,并需要从 DataSet 中获取数据。 由于它是用户可编辑的配置文件,因此字段可能存在也可能不存在。 为了很好地处理丢失的字段,我想确保 DataRow 中的每一列都存在并且不是 DBNull。
我已经检查了 DBNull,但我不知道如何确保该列存在而不引发异常或使用循环遍历所有列名称的函数。 做到这一点的最佳方法是什么?
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 missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull.
I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
DataSet.Tables(0).Columns.Contains(name)
来检查DataTable
是否包含具有特定名称的列。You can use
DataSet.Tables(0).Columns.Contains(name)
to check whether theDataTable
contains a column with a particular name.确定列是否存在的另一种方法是在将列名传递给列时检查从
Columns
集合索引器返回的值是否为Nothing
:此方法可能优于当以下代码随后需要获取该
DataColumn
以便进一步使用时,使用Contains("ColumnName")
方法。 例如,您可能想知道哪种类型在列中存储了值:在这种情况下,此方法可以节省您对
Contains("ColumnName")
的调用,同时使您的代码成为干净一点。Another way to find out if a column exists is to check for
Nothing
the value returned from theColumns
collection indexer when passing the column name to it:This approach might be preferred over the one that uses the
Contains("ColumnName")
method when the following code will subsequently need to get thatDataColumn
for further usage. For example, you may want to know which type has a value stored in the column:In this case this approach saves you a call to the
Contains("ColumnName")
at the same time making your code a bit cleaner.您可以使用 try ... catch 语句封装代码块,当您运行代码时,如果该列不存在,它将引发异常。 然后,您可以找出它抛出的特定异常,并根据需要以不同的方式处理该特定异常,例如返回“未找到列”。
You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".
DataRow 的优点在于它们将基础表链接到它们。 通过基础表,您可以验证特定行中是否包含特定列。
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.