[英]How to create text boxes and buttons dynamically and get the value from each text box in c#?
[英]Get text value from dynamically creating text boxes
給定多個動態創建的文本框,我想讓用戶填寫文本。 我使用了面板並進行了創作。 找不到文本框的控件。
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;
}
文本框控件為空。 我究竟做錯了什么?
您必須最遲在Page_Load
中重新創建所有控件。 Button1_Click
為時已晚。 因此,在Page_Init
/ Page_Load
重新創建Session["clicks"]
並在Button-Click
-handler中創建單個新控件。
一些代碼:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.