编程语言
首页 > 编程语言> > c# – 获取“无法在Null值上调用此方法或属性”错误

c# – 获取“无法在Null值上调用此方法或属性”错误

作者:互联网

更新1:

这条线上引发了异常:

client_group_details.Add(new ClientGroupDetails(

原始问题:

我有以下代码,我从数据库的30列数据中删除了数据库中的2列.每当任何列返回NULL值时,我都会收到错误:

public class ClientGroupDetails
{
    public String Col2;
    public String Col3;

    public ClientGroupDetails(String m_Col2, String m_Col3)
    {
        Col2 = m_Col2;
        Col3 = m_Col3;
    }

    public ClientGroupDetails() { }
}

[WebMethod()]
public List<ClientGroupDetails> GetClientGroupDetails(string phrase)
{
    var client_group_details = new List<ClientGroupDetails>();

    using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
    {
        using (command = new SqlCommand(@"select col2, col3 where col1 = @phrase", connection))
        {
            command.Parameters.Add("@phrase", SqlDbType.VarChar, 255).Value = phrase;

            connection.Open();
            using (reader = command.ExecuteReader())
            {
                int Col2Index = reader.GetOrdinal("col2");
                int Col3Index = reader.GetOrdinal("col3");

                while (reader.Read())
                {
                    client_group_details.Add(new ClientGroupDetails(
                        reader.GetString(Col2Index),
                        reader.GetString(Col3Index)));
                }
            }
        }
    }

    return client_group_details;
}

我得到的错误是:

数据是空的.无法在Null值上调用此方法或属性.

我不知道该怎么做来处理NULL值,因为上面的代码是一个精简版本.

有谁知道如何解决这个问题?

解决方法:

这是因为不应该在DBNull值上调用reader.GetString.尝试更改代码,如下所示:

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index)));

标签:c,net-3-5,c-3-0,asp-net-3-5,asmx
来源: https://codeday.me/bug/20190530/1184337.html