无法隐式转换类型&system; web.web.ui.control'到' system.web.ui.webcontrols.checkbox

时间:2017-04-25 10:15:05

标签: c# asp.net

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

我想查看系统的座位可用性,以便用户可以选中显示时间,以便用户选择显示时间系统检查数据库中的可用座位并禁用其他用户预订的CheckBox

所以我的问题是我在ch = Page.FindControl(dt9.Rows[i].ItemArray[0].ToString());上收到错误:

  

无法隐式转换类型&system; web.web.ui.control&#39;到&#39; system.web.ui.webcontrols.checkbox&#39;

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

Page.FindControl返回Control,您试图将其隐式转换为CheckBox。您需要明确地将其转换为CheckBox

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

或者更好地使用as投射并使用null支票:

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

附注:您将ch实例化为new CheckBox,然后立即将其更改为FindControl带回的那个。不需要那样做,只需:

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

答案 1 :(得分:0)

只需键入强制转换为复选框,如下所示:

 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;
}
}
相关问题