Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法隐式转换类型';system.web.ui.control';至';system.web.ui.webcontrols.checkbox inti=0; 对于(i=0;i_C#_Asp.net - Fatal编程技术网

C# 无法隐式转换类型';system.web.ui.control';至';system.web.ui.webcontrols.checkbox inti=0; 对于(i=0;i

C# 无法隐式转换类型';system.web.ui.control';至';system.web.ui.webcontrols.checkbox inti=0; 对于(i=0;i,c#,asp.net,C#,Asp.net,只需键入cast to复选框,如下所示: int i = 0; for (i = 0; i <= dt9.Rows.Count - 1; i++) { CheckBox ch = new CheckBox(); ch = Page.FindControl(dt9.Rows[i].ItemArray[0].ToString()); <--- ERROR ch.Checked = true; ch.Enabled = false; ch.Bac

只需键入cast to复选框,如下所示:

int i = 0;

for (i = 0; i <= dt9.Rows.Count - 1; i++)
{
    CheckBox ch = new CheckBox();

    ch = Page.FindControl(dt9.Rows[i].ItemArray[0].ToString()); <--- ERROR
    ch.Checked = true;
    ch.Enabled = false;
    ch.BackColor = System.Drawing.Color.Chocolate;
}

for(i=0;i
页面。FindControl
返回
控件
,您试图将其隐式转换为
复选框
。您需要将其显式转换为
复选框

 for (i = 0; i <= dt9.Rows.Count - 1; i++)
{
    CheckBox ch = new CheckBox();

    ch =  (CheckBox)Page.FindControl(dt9.Rows[i].ItemArray[0].ToString()); <--- ERROR
if (ch != null)
{
    ch.Checked = true;
    ch.Enabled = false;
    ch.BackColor = System.Drawing.Color.Chocolate;
}
}
或者更好地使用
as
强制转换,并使用
null
检查:

ch = (CheckBox)Page.FindControl(dt9.Rows[i].ItemArray[0].ToString());

旁注:您将
ch
实例化为
新复选框
,然后立即将其更改为
FindControl
返回的复选框。无需执行此操作,只需执行以下操作:

ch = Page.FindControl(dt9.Rows[i].ItemArray[0].ToString()) as CheckBox;
if (ch == null)
{
    //The control is not a checkbox, handle it here
}

如果来自
FindControl
Control
不是类型
CheckBox
的,则编辑的
null
检查将不起作用。它将引发异常。@TheLethalCoder,我不这么认为。。请在visual Studio中尝试。:)如果
FindControl
返回
null
,不确定是否可能,则检查可以。但是,如果它返回另一个控件,
按钮
,则强制转换将引发异常,因为
按钮
的类型不是
复选框
。仅当系统获得具有该ID的复选框时,才会键入强制转换,否则rwise它将返回NULL..它不会抛出异常如果
FindControl
返回
按钮,代码中会发生什么?
CheckBox ch = Page.FindControl(dt9.Rows[i].ItemArray[0].ToString()) as CheckBox;