我在按钮点击事件上创建一些动态文本框,在另一个按钮上点击我想使用findcontrol方法获取该文本框的数据
public void addDepartmentBtn_Click(object sender, EventArgs e)
{
int count = Convert.ToInt32(countTxtBx.Text);
lblErrorMsg.Text = "";
if (Convert.ToInt32(countTxtBx.Text) <= 5)
{
for (int i = 0; i < count; i++)
{
Label lb = new Label();
TextBox tb = new TextBox();
tb.ID = "Textbox_" + i;
lb.ID = "Label_" + i;
lb.Text = "Enter Departnment Name: " + Convert.ToInt32(i + 1);
pnlMain.Controls.Add(new LiteralControl("<br>"));
pnlMain.Controls.Add(lb);
pnlMain.Controls.Add(new LiteralControl("  "));
pnlMain.Controls.Add(tb);
pnlMain.Controls.Add(new LiteralControl("<br><br>"));
lblErrorMsg.Text = Convert.ToInt32(i + 1) + " Departments Created Successfully";
//string str = string.Empty;
//TextBox myTB = (TextBox)pnlMain.FindControl("Textbox_" + i);
//str = myTB.Text;
//Response.Write(str);
}
}
else
{
lblErrorMsg.Text = "You cannot create more than 5 Departments at once:";
}
}
在按钮2上单击:
protected void Button2_Click(object sender, EventArgs e)
{
string alltextdata = null;
for (int i = 0; i < 5; i++)
{
Control controltxt = FindControl("Textbox_"+i);
if (controltxt != null)
{
TextBox txttemp = (TextBox)controltxt;
alltextdata = txttemp.Text;
}
}
}
但我的find控制方法总是显示null我检查我的html页面查看源,它显示我的每个东西都正确我的文本框名称和id是“Textbox_0”,Textbox_1等
我在做错了吗?请帮忙答案 0 :(得分:2)
当您动态添加控件时,它不会在回发后添加到控件树中(button2回发)。在单击addDepartmentBtn之后,您需要在任何回发中的Page_Load事件中再次添加它。
在ViewState中单击保存该按钮并在Page_Load:
中进行检查public void addDepartmentBtn_Click(object sender, EventArgs e)
{
ViewState["addDepartmentBtn_Clicked"] = true;
AddTextBoxes();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(ViewState["addDepartmentBtn_Clicked"]) == true)
AddTextBoxes();
}
public void AddTextBoxes()
{
int count = Convert.ToInt32(countTxtBx.Text);
lblErrorMsg.Text = "";
if (Convert.ToInt32(countTxtBx.Text) <= 5)
{
for (int i = 0; i < count; i++)
{
Label lb = new Label();
TextBox tb = new TextBox();
tb.ID = "Textbox_" + i;
lb.ID = "Label_" + i;
lb.Text = "Enter Departnment Name: " + Convert.ToInt32(i + 1);
pnlMain.Controls.Add(new LiteralControl("<br>"));
pnlMain.Controls.Add(lb);
pnlMain.Controls.Add(new LiteralControl("  "));
pnlMain.Controls.Add(tb);
pnlMain.Controls.Add(new LiteralControl("<br><br>"));
lblErrorMsg.Text = Convert.ToInt32(i + 1) + " Departments Created Successfully";
//string str = string.Empty;
//TextBox myTB = (TextBox)pnlMain.FindControl("Textbox_" + i);
//str = myTB.Text;
//Response.Write(str);
}
}
else
{
lblErrorMsg.Text = "You cannot create more than 5 Departments at once:";
}
}
答案 1 :(得分:0)
在调用findcontrol方法之前,必须再次加载该contro,因为它是在每次回发时动态创建的。这些不像我们在Page_Init下创建的静态控件。动态控件在Page_Load事件下创建。