简体   繁体   English

当Checkbox值为null时。 程序抛出此错误“对象不能从DBNull强制转换为其他类型。”

[英]When Checkbox value is null. Program throws this error“ Object cannot be cast from DBNull to other types.”

When the checkbox value in database is null it throws error. 当数据库中的复选框值为null时,将引发错误。 When it is 0 or 1 it works as expected. 当它是01它将按预期工作。

if (Request.QueryString["Sckey"] != null && Request.QueryString["Sckey"].ToString() != "")
{
    string str_sql1 = "select ScenarioSeq,ScenarioName,FileName,ScenarioNotes,IsUpperCase from Scenario where ScenarioKey=@ScenarioKey;";
    SqlCommand cm = new SqlCommand(str_sql1);
    cm.Parameters.AddWithValue("@ScenarioKey", str_ScKey);
    DataSet ds2 = this.DA.GetDataSet(cm);

    DataRow dr = ds2.Tables[0].Rows[0];
    txt_ScenarioName.Text = dr["ScenarioName"].ToString();
    txt_ScenarioNotes.Text = dr["ScenarioNotes"].ToString();
    ch_Uppercase.Checked = Convert.ToBoolean(dr["IsUpperCase"]);     
}

Null in the terms of RDBMS has a special meaning , it stands for unknown , invalid , can't be applied to etc., and that's why can't be cast (what bool value ( true , false ) should be used for unknown ?). RDBMS术语中的Null具有特殊含义 ,代表未知无效不能应用于等,这就是为什么不能bool (对于未知变量应使用什么bool值( truefalse )? )。 Try dr.IsNull("IsUpperCase") : 试试dr.IsNull("IsUpperCase")

 ch_Uppercase.Checked = !dr.IsNull("IsUpperCase") && Convert.ToBoolean(dr["IsUpperCase"]);

Do something like this.. 做这样的事..

ch_Uppercase.Checked = 
     Convert.ToBoolean(dr["IsUpperCase"] == DBNull.Value? 0: dr["IsUpperCase"]);
int number;
bool result = Int32.TryParse(dr["IsUpperCase"], out number);
ch_Uppercase.Checked = number;

像这样更正它。

ch_Uppercase.Checked = !dr.IsNull ? Convert.ToBoolean(dr["IsUpperCase"]) : false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将对象从DBNull强制转换为其他类型。 读取器读取空值时出错 - Object cannot be cast from DBNull to other types. Error when a null value is read by the Reader 错误。 '对象不能从 DBNull 转换为其他类型。' C# 与方法 sum() - Error! 'Object cannot be cast from DBNull to other types.' C# with method sum() System.InvalidCastException:“无法将对象从 DBNull 转换为其他类型。” 从数据库转换为 Object - System.InvalidCastException: 'Object cannot be cast from DBNull to other types.' in Conversion from Database to Object system.invalidcastexception 'object cannot be cast from dbnull to other types.' - system.invalidcastexception 'object cannot be cast from dbnull to other types.' “无法将对象从DBNull强制转换为其他类型” - “Object cannot be cast from DBNull to other types” 无法将对象从DBNull强制转换为其他类型 - The Object cannot be cast from DBNull to other types Object 不能从 DBNull 转换为其他类型 - Object cannot be cast from DBNull to other types 收到错误“无法将对象从DBNull强制转换为其他类型” - Getting error “Object cannot be cast from DBNull to other types” 我有一个错误对象无法从DBNull强制转换为其他类型 - Im having an error Object cannot be cast from DBNull to other types 无法将对象从DBNull强制转换为显示的其他类型错误? - Object cannot be cast from DBNull to other types error shown?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM