此方法或属性不能被要求空值&QUOT

此方法或属性不能被要求空值&QUOT

本文介绍了获得"此方法或属性不能被要求空值"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新1:

该异常被抛出在这条线:

The exception is being thrown on this line:

client_group_details.Add(new ClientGroupDetails(

原题:

我有以下的code,我已经剥离下来的数据,30列从数据库中只有2列从数据库中。我得到一个错误,每当任一列返回NULL值:

I have the following code which I have stripped down from 30 columns of data from the database to just 2 columns from the database. I get an error whenever any of the columns return a NULL value:

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;
}

我得到的错误是:

The error I am getting is:

数据为空。此方法或属性不能被要求空值。

Data is Null. This method or property cannot be called on Null values.

我不知道该怎么做在这里处理空值作为code以上是一个精简版本。

I'm not sure what to do here to deal with NULL values as the code above is a stripped down version.

任何人都知道如何解决这个问题呢?

Anyone know how to solve this issue?

推荐答案

这是因为 reader.GetString 不应该叫上的DBNull 值。试着改变你的code如下:

This is because reader.GetString should not be called on DBNull values. Try changing your code as follows:

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

这篇关于获得&QUOT;此方法或属性不能被要求空值&QUOT;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:38