0

请先原谅我蹩脚的英语。

好吧,antiduh 的调试方法帮助我了解我的代码发生了什么,感谢所有加入讨论的人。


当我使用 OdbcDataReader.GetBoolean 单时,没问题,如下所示:

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
checkBox1.Checked = reader.GetBoolean(0);                

不会发生任何问题。

但!!

我需要确定该列是否为 Null,因此我使用如下 if 语句:

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
    checkBox1.Checked = reader.GetBoolean(0);

在 reader.GetBoolean(0) 上会出现 InvalidCastException 错误

我不知道这个问题,有人可以帮助我吗?请~


根据 antiduh 的宝贵意见,我发现 if reader.GetValue(0) 不在 if 语句中,如下所示:

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
var foo = reader.GetValue(0);

它会返回 True 或 False。

但是如果 reader.GetValue(0) 在 if 语句的内部,如下所示:

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
{
    var foo = reader.GetValue(0);
}

它将返回 1 或 0。

So if I use GetBoolean to transform 1 or 0 to bool data type,will occur InvalidCastException.

Now I know what happen on my code,but still don't know what the difference between two codes.


Thanks antiduh's valuable comment again,

I try this code that antiduh provide below:

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
{
    try
    {
        checkBox1.Checked = reader.GetBoolean(0);
    }
    catch ( InvalidCastException e ) {
        object doubleCheck = reader.GetValue(0);
        Console.WriteLine( "Tried to cast this type: " + doubleCheck.GetType() );
    }
}

It wiil return: Tried to cast this type:System.String

And doubleCheck.ToString() is 1 or 0.

4

1 回答 1

0

Its likely that the value in that row and column is not actually a bool. Add some temporary debugging code to catch the exception and call GetValue instead, and look to see what you're actually getting back.

OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
{
    try {
        checkBox1.Checked = reader.GetBoolean(0);
    }
    catch ( InvalidCastException e ) {
        object doubleCheck = reader.GetValue(0);

        Console.WriteLine( "Tried to cast this type: " + doubleCheck.GetType() );
    }
}
于 2013-06-27T04:29:33.767 回答