2012-03-19 86 views
0

我想向表中添加一些動態文本框並讓它們觸發事件。 我沒有問題創建文本框,或訪問有關他們的信息,但他們不想觸發事件。添加到動態文本框中的動態事件不會觸發

List<string> txtNames = new List<string>(); 
    txtNames.Add("txtId"); 
    txtNames.Add("txtName"); 
    txtNames.Add("txtQty"); 
    txtNames.Add("txtUnitPrice"); 
    txtNames.Add("txtExtendedPrice"); 

    Panel1.Controls.Add(new LiteralControl("\t<tr>\n")); 
    TextBox txt; 
    foreach (string s in txtNames) 
    { 
     txt = new TextBox(); 
     txt.CopyBaseAttributes(Textbox1); 
     txt.Text = ""; 
     txt.BorderWidth = 0; 
     txt.ID = s + row; 

     Panel1.Controls.Add(new LiteralControl("\t\t<td>")); 
     Panel1.Controls.Add(txt); 
     Panel1.Controls.Add(new LiteralControl("</td>\n")); 

     txt.AutoPostBack = true; 
     txt.TextChanged += new EventHandler(txt_TextChanged); 

     txt.Text = s; 
     count++; 
    } 
    Panel1.Controls.Add(new LiteralControl("\t</tr>\n")); 
    row++; 

(面板是一個HTML表格內)

此代碼是在當頁面不回發或者單擊一個按鈕來添加文本框的行調用的函數。

將文本框保存到會話中,然後重新加載到page_load上。

我試過做一個沒有在for循環中創建的測試文本框,並且確實觸發了文本更改事件。

編輯: 從保存的會話加載文本框的時候,現在他們正在觸發功能我試圖重新添加文本改變事件。

+0

凡上面的代碼在哪裏? Page_Load中? – Dante 2012-03-19 14:17:09

+0

它在一個函數中被調用,當頁面不回發,或者當我點擊一個按鈕來添加另一行文本框。 – anthro 2012-03-19 14:29:06

+0

工作的測試文本框是否也保存並重新創建? – AGuyCalledGerald 2012-03-19 14:48:14

回答

0

應該在Page_Load中重新創建控件和事件,因爲動態控件在請求後會丟失。

+0

我將它們保存到會話中,然後將它們重新加載到Page_load上 – anthro 2012-03-19 14:26:50

+0

如何重新加載? – bodee 2012-03-19 14:39:35

+0

我在找到所有的文本框,將它們保存到列表中並將該列表保存到會話中。然後加載我只是採取文本框的列表,並以幾乎完全相同的方式將它們添加回來。 – anthro 2012-03-19 14:42:43

1

您應該將裏面的OnInit而不是頁面加載你的方法調用,並且只設置Text屬性時不回發

protected override void OnInit(EventArgs e) 
    { 
     base.OnInit(e); 
     int row = 0; 
     int count = 0; 
     List<string> txtNames = new List<string>(); 
     txtNames.Add("txtId"); 
     txtNames.Add("txtName"); 
     txtNames.Add("txtQty"); 
     txtNames.Add("txtUnitPrice"); 
     txtNames.Add("txtExtendedPrice"); 

     Panel1.Controls.Add(new LiteralControl("\t<tr>\n")); 
     TextBox txt; 
     foreach (string s in txtNames) 
     { 
      txt = new TextBox(); 
      //txt.CopyBaseAttributes(Textbox1); 
      txt.BorderWidth = 0; 
      txt.ID = s + row; 

      Panel1.Controls.Add(new LiteralControl("\t\t<td>")); 
      Panel1.Controls.Add(txt); 
      Panel1.Controls.Add(new LiteralControl("</td>\n")); 

      txt.AutoPostBack = true; 
      txt.TextChanged += (sndr, evt) => { Response.Write(((Control)sndr).ID + " --- " + ((TextBox)sndr).Text); }; 

      if(!IsPostBack) 
       txt.Text = s; 
      count++; 
     } 
     Panel1.Controls.Add(new LiteralControl("\t</tr>\n")); 
     row++; 

    } 
相關問題