Please forgive my broken English first.
Well,antiduh's method of debug helps me to know what happen on my code,thanks everyone who join discuss.
When I use OdbcDataReader.GetBoolean single,it's OK and no problem,just like below:
OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
checkBox1.Checked = reader.GetBoolean(0);
no problem wiil occur.
BUT!!
I need to ascertain the column is Null or not,so I use if-statement as below:
OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
checkBox1.Checked = reader.GetBoolean(0);
It will occur InvalidCastException error on reader.GetBoolean(0)
I have no idea about this problem,does somebody can help me? please~
According to antiduh's valuable comment, I found that if reader.GetValue(0) isn't in if-statement as below:
OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
var foo = reader.GetValue(0);
It wiil return True or False.
But if reader.GetValue(0) is in interior of if-statement as below:
OdbcDataReader reader = CMD.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0) == false)
{
var foo = reader.GetValue(0);
}
It will return 1 or 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.
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() );
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.