运行时生成控件给出错误 [英] Runtime generate control give error
问题描述
大家好,
我正在创建一个网站.
我有一个面板,按钮和组合框.
组合框用于选择否.运行时生成的文本框的数量,该按钮用于在文本框中显示所有运行时生成的文本.
我已经试过了这段代码,但它给出了一个错误:-
Hi All,
I am creating a website.
I have a Panel, button, and combo-box.
The combobox is used for selecting no. of textbox you generate at runtime and the button is used for displaying all runtime generated text in the textbox.
I have tried this code but it gives an error:-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class NewFolder1_AutoGenerate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int indexcount=int.Parse(DropDownList1.SelectedValue);
for (int i = 0; i < indexcount; i++)
{
TextBox t1 = new TextBox();
t1.ID = "text" + i.ToString();
Panel1.Controls.Add(t1);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string s1 = null;
foreach (Control ctrl in Panel1.Controls)
{
TextBox t1 = (TextBox)ctrl;
s1 += t1.Text + "/n";
}
Response.Write(Panel1.Controls.Count.ToString());
Response.Write(s1);
}
}
上面的代码生成了运行时控件,但是当我单击按钮时,它不会显示所有文本框文本.
它给出错误:-
(InvalidCastException)无法将类型为"System.Web.UI.LiteralControl"的对象转换为类型为"System.Web.UI.WebControls.TextBox".
帮帮我.
The above code generates the runtime control but when I click the button it does not display the all textbox text.
It give error:-
(InvalidCastException) Unable to cast object of type ''System.Web.UI.LiteralControl'' to type ''System.Web.UI.WebControls.TextBox''.
Help me.
推荐答案
那是因为面板中还有其他控件,它们不是Textboxes-在使用它们之前请检查一下:
That''s because there are other controls in the panel, which are not Textboxes - check before you use them:
foreach (Control ctrl in Panel1.Controls)
{
TextBox t1 = ctrl as TextBox;
if (t1 != null)
{
s1 += t1.Text + "/n";
}
}
您必须在投射之前检查控件.
You have to check the control before casting.
if (ctrl.GetType().Name.ToString()=="TextBox")
{
TextBox t1 = (TextBox)ctrl;
s1 += t1.Text + "/n";
}
这篇关于运行时生成控件给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!