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

五迷三道 提交于 2019-12-05 11:49:41

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

You need to use IsDbNull to check if the column is null before calling GetString, something like:

string s1, s2;

if (reader.IsDbNull(Col1Index) == false)
{
   s1 = reader.GetString(Col1Index);
}

if (reader.IsDbNull(Col2Index) == false)
{
   s2 = reader.GetString(Col2Index);
}

client_group_details.Add(new ClientGroupDetails(s1, s2));

There are a couple ways you can do this, but I think the best approach for your code is to add a simple function call to your SQL text - namely, the IsNull function.

Here's a link to the manual page for this: IsNull MSDN reference

Basically, you'll change your SQL text to look similar to this:

"select IsNull(col2, ''), IsNull(col3, '') where col1 = @phrase"

And now if the column in the DB is null, it will instead return a blank string.

You can also set default values on your columns, or you can check for System.DBNull.Value on your code side.

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!