C# DataTable ItemArray 返回“{}” - 如何测试空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/707658/
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
C# DataTable ItemArray returns '{}' - how can I test for null value?
提问by Nick Josevski
I have a DataTable resultSet;
- I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.
我有一个DataTable resultSet;
- 我正在尝试检查字段是否为空,但返回一个“{}”(空集?)对象。涉及“{}”的搜索没有产生任何合适的解决方案。
This is the code that isn't working as expected when the "fk_id" field is null:
这是当“fk_id”字段为空时无法按预期工作的代码:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
//never reaches here
}
Note: using an int index instead of the Columns.IndexOf()
isn't the issue.
注意:使用 int 索引而不是 theColumns.IndexOf()
不是问题。
Also does the "{}" have some other name in C#?
“{}”在 C# 中还有其他名称吗?
采纳答案by Matt Hamilton
To check a column for DBNull in a DataSet, you can use the IsNullmethod:
要检查 DataSet 中的 DBNull 列,您可以使用IsNull方法:
if (resultSet.Rows[0].IsNull("fk_id"))
Your comparison against null
is probably failing because DataSets don't use null
to represent a "database NULL" value - they use DBNull.Value. If you need your code to work the way you've presented it, try this:
您的比较null
可能失败,因为 DataSet 不用于null
表示“数据库 NULL”值 - 它们使用DBNull.Value。如果您需要您的代码按照您呈现的方式工作,请尝试以下操作:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == DBNull.Value)
回答by Adei
try
{
if (DT.Rows[0][0] != null)
{
//your code
}
}
catch
{
MessageBox.Show("AUTHANICATION FAILED.");
}
回答by Khalid Rafique
Please use:
请用:
dataTable.Select("FieldName is NULL")
this will give you the DataRows with null values in FieldName column.
这将为您提供 FieldName 列中具有空值的 DataRows。