无法将类型为“System.Web.UI.HtmlControls.HtmlInputCheckBox”的对象强制转换为“System.Web.UI.WebControls.CheckBox”。 [英] Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputCheckBox' to type 'System.Web.UI.WebControls.CheckBox'.
问题描述
bool isSelected = false ;
foreach (GridViewRow i in DataGridTrans.Rows)
{
CheckBox cb = new CheckBox();
cb =(CheckBox)i.FindControl( ChkBox1); // 显示如上所述的错误
if (cb!= null && cb.Checked)
{
isSelected = 真跨度>;
break ;
}
}
如果查看标记,您会看到复选框定义为
< 输入 类型 = 复选框 / >
而不是
< asp:checkbox xmlns:asp < span class =code-keyword> = #unknown / >
显然你是ca不要在两者之间转换 - 你必须决定使用什么并坚持下去......
尝试如下:
var cb =(HtmlInputCheckBox)row.FindControl( ChkBox1);
投射将取决于你在aspx中如何声明它
你的ChkBox1可能是
< input type =checkboxrunat =server/>
转换为HtmlInputCheckBox。替代方案是
< asp:Checkbox runat =server/>
转换为Checkbox。如果你想保留你的标记,你需要在代码隐藏中使用HtmlInputCheckBox,而不是Checkbox
// 不需要这一行
// CheckBox cb = new CheckBox();
HtmlInputCheckBox cb =(HtmlInputCheckBox)i.FindControl( ChkBox1); // 显示如上所述的错误
如果(cb!= null && cb.Checked)
要使用这个你需要
使用System.Web.UI.HtmlControls;
位于页面顶部。
bool isSelected = false;
foreach(GridViewRow i in DataGridTrans.Rows)
{
CheckBox cb = new CheckBox();
cb = (CheckBox)i.FindControl("ChkBox1");//error showing cast as mentioned above
if (cb != null && cb.Checked)
{
isSelected = true;
break;
}
}
If you look at your markup you will see that the checkbox defined as
<input type="checkbox" />
and not as
<asp:checkbox xmlns:asp="#unknown" />
Obviously you ca nnot convert between the two -you have to decide what to use and stick to that...
Try it like:
var cb = (HtmlInputCheckBox)row.FindControl("ChkBox1");
The casting will depend on how have you declared it in your aspx
Your "ChkBox1" is probably
<input type="checkbox" runat="server"/>
which gets converted to HtmlInputCheckBox. The alternative is
<asp:Checkbox runat="server"/>
which gets converted to Checkbox. If you want to keep your markup as it is you need to use the HtmlInputCheckBox in your code-behind, not Checkbox
// don't need this line // CheckBox cb = new CheckBox(); HtmlInputCheckBox cb = (HtmlInputCheckBox)i.FindControl("ChkBox1");//error showing cast as mentioned above if (cb != null && cb.Checked)
To use this you need
using System.Web.UI.HtmlControls;
at the top of your page.
这篇关于无法将类型为“System.Web.UI.HtmlControls.HtmlInputCheckBox”的对象强制转换为“System.Web.UI.WebControls.CheckBox”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!