c# - 测试某个值是否为空

标签 c#

我有以下代码,但我遇到了问题。在我的 While 中,必须测试 r["Varandas"] 是否不为空。在特定的 imovel_id 中,r["Varandas"] 为 null,但仍然通过我的代码,然后我得到一个异常错误,因为无法解析为 int the r["Varandas"] 因为它为 null,但为什么他通过通过我的 While 循环中的第一个 IF?

        string s = "SELECT * "
            + "FROM San_Imovel_Caracteristica "
            + "WHERE Imovel_Id = " + imovel_id + " ";

        SqlConnection c = new SqlConnection(conn.Con);
        SqlCommand cmd = new SqlCommand(s, c);
        c.Open();
        SqlDataReader r = cmd.ExecuteReader();

        while (r.Read())
        {
            if (r["Varandas"] != null)
            {
                if (Convert.ToInt32(r["Varandas"].ToString()) > 0)
                {
                    XmlElement itemImovel1 = doc.CreateElement("itemImovel");
                    caracteristicasImovel.AppendChild(itemImovel1);
                    itemImovel1.InnerText = "varanda";
                }
            }
         }

最佳答案

null 数据库中的值有其自己的特殊类型:

if (r["Varandas"] != DBNull.Value && r["Varandas"] != null)

为了让它更优雅,您可以为 DataRow 类编写一些简单的函数甚至扩展。

关于c# - 测试某个值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10089120/

相关文章:

c# - 使用来自不同程序集的自定义 UserControl 时出现 "The member is not recognized or is not accessible"

c# - 如何解析具有嵌套元素(complexType 和 simpleType 元素和属性)的 xsd 文件?

c# - 如何使用带有泛型参数的类型作为约束?

c# - Visual Studio 模板 "Generate Method Stub"

c# - 如何在 winrt 中按字节限制文本框最大长度?

c# - 如何获取 sql 结果并在标题中填充标签?

c# - SQL 语句转换为 LinQ 语句

c# - StackOverflow 异常 CSVHelper 编写器

c# - 是什么导致 user.config 为空?以及如何在不重新启动的情况下恢复?

c# - 使用 CQRS 方法处理并发