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?
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With