Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "This method or property cannot be called on Null values" error

UPDATE 1:

The exception is being thrown on this line:

client_group_details.Add(new ClientGroupDetails(

ORIGINAL QUESTION:

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.

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?

like image 783
oshirowanen Avatar asked Jan 17 '23 10:01

oshirowanen


1 Answers

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)));
like image 96
Sergey Kalinichenko Avatar answered Feb 12 '23 04:02

Sergey Kalinichenko