"无法转换对象"同时通过编程方式创建文本框循环 [英] "Unable to cast object" while looping through programatically created textboxes

查看:187
本文介绍了"无法转换对象"同时通过编程方式创建文本框循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态创建一些文本框 -

I have some Textboxes that are created dynamically --

int i = 1;
while (reader.Read())
{
    System.Web.UI.WebControls.TextBox textBox = new System.Web.UI.WebControls.TextBox();
    textBox.ID = reader["field_id"].ToString();
    textBox.Enabled = false;
    HtmlGenericControl div = new HtmlGenericControl("div");

    if(i%2 != 0)
        div.Attributes.Add("style", "margin-right:120px;padding-bottom:20px;");

    if (i % 2 == 0)
        div.Attributes.Add("style", "padding-bottom:20px;");

    div.Attributes.Add("class", "inline fourcol");
    div.InnerHtml = "<label>" + reader["field"] + "</label>"; 
    div.Controls.Add(textBox);
    panelId.Controls.Add(div);
    textBox.Text = reader["field_value"].ToString();
    ++i;
}

这正常工作(至少我敢肯定 - 他们显示他们应该如何)。但是,当我试图通过他们循环,使它们,或让他们的价值观,我得到一个无法转换型System.Web.UI.LiteralControl对象键入'System.Web.UI.WebControls。文本框。的错误。

That works fine (at least i'm sure -they show up how they should). But when i try to loop through them to enable them, or get their values, i get an "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'. " error.

这就是我一直在试图做到这一点 -

This is how i've been trying to do it --

public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
    foreach (System.Web.UI.WebControls.TextBox t in panel.Controls)
    {
        t.Enabled = true;
    }
}

谢谢!

推荐答案

您是把每一个文本框一个分区的控制是在 HtmlGenericControl ,然后将面板控件内。所以,首先你必须搜索 HtmlGenericControl panelId.Controls

You are putting each textbox inside a "div" control which is HtmlGenericControl, then inside the panel control. So first you must search for the HtmlGenericControl inside panelId.Controls

一个样本code可以帮助你:

A sample code that might help you:

public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
    foreach (Control c in panelId.Controls)
            {
                if (c is HtmlGenericControl)
                {
                    foreach (var textbox in c.Controls.OfType<TextBox>()) //ofType returns IEnumerable<TextBox>
                        textbox.Enabled = true;
                }
            }
} 

这篇关于&QUOT;无法转换对象&QUOT;同时通过编程方式创建文本框循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆