考虑到多个动态创建的文本框,我想让用户填写文本。 我使用了Panel和创作工作。找不到文本框的控件。
ASPX
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Adauga autor" OnClick="Button1_Click" />
</div>
创建文本框
protected void Button1_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
Session["clicks"] = rowCount;
for (int i = 1; i <= rowCount; i++)
{
TextBox TxtBoxA = new TextBox();
Label lblA = new Label();
TxtBoxA.ID = "TextBoxA" + i.ToString();
lblA.ID = "LabelA" + i.ToString();
lblA.Text = "Label" + i.ToString() + ": ";
Panel1.Controls.Add(lblA);
Panel1.Controls.Add(TxtBoxA);
Panel1.Controls.Add(new LiteralControl("<br />"));
}
}
获取文字
int rowCount = Convert.ToInt32(Session["clicks"]);
for (int i = 1; i <= rowCount; i++)
{
string item = "TextBoxA" + i.ToString();
Control foundControl = FindControl(item, Page.Controls);
TextBox TB = (TextBox)foundControl;
string txt = TB.Text;
}
+
public static Control FindControl(string controlId, ControlCollection controls)
{
foreach (Control control in controls)
{
if (control.ID == controlId)
return control;
if (control.HasControls())
{
Control nestedControl = FindControl(controlId, control.Controls);
if (nestedControl != null)
return nestedControl;
}
}
return null;
}
Textbox Control为null。我做错了什么?
答案 0 :(得分:0)
您最迟必须在Page_Load
中重新创建所有控件。 Button1_Click
为时已晚。因此,在Session["clicks"]
/ Page_Init
中重新创建Page_Load
并在Button-Click
- 处理程序中创建单个新控件。
一些代码:
protected void Page_Init(Object sender, EventArgs e)
{
RecreateControls();
}
private void RecreateControls()
{
int rowCount = Convert.ToInt32(Session["clicks"]);
CreateControls(rowCount);
}
private void AddControl()
{
int rowCount = Convert.ToInt32(Session["clicks"]);
CreateControls(1);
Session["clicks"] = rowCount++;
}
private void CreateControls(int count)
{
for (int i = 1; i <= count; i++)
{
TextBox TxtBoxA = new TextBox();
Label lblA = new Label();
TxtBoxA.ID = "TextBoxA" + i.ToString();
lblA.ID = "LabelA" + i.ToString();
lblA.Text = "Label" + i.ToString() + ": ";
Panel1.Controls.Add(lblA);
Panel1.Controls.Add(TxtBoxA);
Panel1.Controls.Add(new LiteralControl("<br />"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
AddControl();
}