为避免异常,请先检查您的对象是否为空,然后再尝试对其调用方法。检查...
dataTABLE != null
Cells[0].Value != null
Cells[1].Value != null
话虽如此,您询问了完成任务的最佳方法,所以这里有一些其他的事情需要考虑。
您可以使用dataTable.AsEnumerable().Any( dr => ...); 之类的方式遍历数据表,以查看是否已经存在任何符合您条件的行。
当您需要将字符串与其他可能为 null 的字符串或对象进行比较时,您需要仔细考虑您的要求以及 null 引用对您意味着什么。
如果cell[0].value == null 还想继续比较MyServerChecked 吗?如果cell[0].value == null 和MyServerChecked == null 那么它们应该被认为是平等的吗?
同样,你想如何处理空字符串?空字符串应该被认为等于null吗?
这是一个简单的入门解决方案。如果单元格为空,则不会尝试比较它们。这可能不是您想要的行为,但就像我说的那样,请考虑 什么 空值和空字符串对您的特定场景意味着什么,并相应地编写代码。
string MyServerChecked = "Something";
string ServiceName = service.ServiceName.ToString();
if (dataTable != null)
{
foreach (DataGridViewRow row in dataTable.Rows)
{
if (row.Cells[0].Value != null
&& row.Cells[1].Value != null
&& string.Equals(row.Cells[0].Value.ToString(), MyServerChecked, StringComparison.OrdinalIgnoreCase)
&& string.Equals(row.Cells[1].Value.ToString(), ServiceName, StringComparison.OrdinalIgnoreCase))
{
// Row already exists...
}
}
}
将重载的string.Equals 方法与StringComparison 枚举类型一起使用意味着您不必自己转换为upper。它还为您提供了一些文化设置的额外选项。查看 MSDN 上的 StringComparison Enumeration 了解更多信息。