[英]Getting IDs and values of dynamically created text boxes on Page_Load
我有一個Web應用程序asp.net。
我正在Page_Load中動態創建54個文本框
這是代碼
protected void Page_Load(object sender, EventArgs e)
{
for(i = 0, i<54, i++)
{
Textbox TestTextbox = new texbox();
TestTextBox.ID = "Reg" + i ;
TestTextBox.Attributes.add("runat","server");
TestTextBoxAttributes.Add("AutoPostBack", "true");
//display to a table called table1 created in the aspx page
}
}
在頁面上,我有一個名為button1的按鈕,以及一個名為“ OnClickEvent”的單擊事件,我想捕獲所有文本框的ID和值。
我使用了Page.Controls.Count,我只得到了1,即我添加到aspx頁面的表,我使用Request.Form獲得了ID,但是我沒有得到值。
我將所有文本框添加到在aspx文件中創建的表中。
您可以遍歷控件,並檢查它們是否為TextBox類型:
for(int i = 0, i<54, i++)) {
var control = Page.FindControl("Reg" + i);
//get the value of the control
}
您沒有將TextBox添加到頁面,因此仍然無法找到它。 其次,將runat=server
和AutoPostBack=true
為字符串也不起作用。 (更不用說您的代碼段充滿了錯誤)
//a loop uses ';', not ','
for (int i = 0; i < 54; i++)
{
//declare a new dynamic textbox = CaSe SeNsItIvE
TextBox TestTextbox = new TextBox();
TestTextbox.ID = "Reg" + i;
//if you want to add attibutes you do it like this
TestTextbox.AutoPostBack = true;
TestTextbox.TextChanged += TestTextbox_TextChanged;
//add the textbox to the page
PlaceHolder1.Controls.Add(TestTextbox);
}
如果要循環所有控件,可以執行以下操作
//loop all the controls that were added to the placeholder
foreach (Control control in PlaceHolder1.Controls)
{
//is it a textbox
if (control is TextBox)
{
//cast the control back to a textbox to access it's properties
TextBox tb = control as TextBox;
string id = tb.ID;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.