得到“无法在空值上调用此方法或属性”错误

问题描述 投票:4回答:4

UPDATE 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值,因为上面的代码是精简版。

任何人都知道如何解决此问题吗?

c# .net-3.5 c#-3.0 asmx asp.net-3.5
4个回答
5
投票

1
投票

0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.