我有一个动态创建一些文本框 -
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;
}
}
}