2011-11-08 24 views
0

我的代碼在C#中快速生成文本框(page_load函數)。我可以在代碼中訪問它嗎?它確實給我編譯錯誤,似乎沒有工作。有人可以驗證嗎?產生額外的問題訪問在飛行中創建的C#中的文本框

代碼

aContent += "<table>"; 
aContent += "<tr><td>lablel </td><td style='bla blah'><input type='textbox' id='col-1' name='col-1'/></td></tr> ... 10 such rows here 
</table>" 

spanMap.InnerHtml = aContent; 

內容物被確定,但recusrive迭代不返回文本框。我打電話像這樣

TextBox txt = (TextBox)this.FindControlRecursive(spanMap, "col-1"); 
// txt = (TextBox) spanMapping.FindControl("col-1"); this does not work too 
if (txt != null) 
{ 
     txt.Text = "A"; 
} 
+1

能否請您發表你正在使用的代碼? – ipr101

+0

你的代碼在哪裏?你是否將它添加到Page控件?您是否在每次回傳中重新添加? –

+0

如何驗證?發佈代碼。 – Nasreddine

回答

2

假設你堅持正確的話,你應該能夠訪問它的代碼隱藏使用FindControl方法。根據其中的控制,則可能必須通過控制層次遞歸搜索:

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id) 
    { 
     return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
     Control t = FindControlRecursive(c, id); 
     if (t != null) 
     { 
      return t; 
     } 
    } 

    return null; 
} 

使用FindControlRecursive

TextBox txt = this.FindControlRecursive(Page.Form, "TextBox1") as TextBox; 
if (txt != null) 
{ 
    string text = txt.Text; 
} 

如果仍然無法使用以上方法找到它,確保您在每次回傳之後創建控制,在Page_Load之前,像OnInit

編輯

我認爲你需要改變你添加內容到容器的方式。如果不使用<span>的,我會用一個Panel,而不是建立標記,只需在代碼隱藏控件添加到面板:

TextBox txt = new TextBox(); 
txt.ID = String.Format("txt_{0}", Panel1.Controls.Count); 
Panel1.Controls.Add(txt);  
+0

所以我猜FindControl是我獲取它的唯一方法。我無法直接訪問它。下面的@sylence確實提到了添加一個參考,但這不是很清楚。 –

+0

是的,你絕對需要'FindControl'來訪問一個動態控件。你不能直接訪問它。 –

+0

我試過這段代碼,但沒有奏效。我的html實際上是在一個跨度內。 'spanMap.InnerHtml = aContent;'。裏面有一張桌子,裏面的桌子是我的文本框。儘管你需要在第二個代碼塊中將'Textbox'更改爲'TextBox(...)'。 –

1

下面是一個例子:

<%@ Page Language="C#" %> 
<script type="text/C#" runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     var textBox = new TextBox(); 
     textBox.ID = "myTextBox"; 
     textBox.Text = "hello"; 
     Form1.Controls.Add(textBox); 
    } 

    protected void BtnTestClick(object sender, EventArgs e) 
    { 
     var textBox = (TextBox)Form1.FindControl("myTextBox"); 
     lblTest.Text = textBox.Text; 
    } 
</script> 
<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <form id="Form1" runat="server"> 
     <asp:LinkButton ID="btnTest" runat="server" Text="Click me" OnClick="BtnTestClick" /> 
     <asp:Label ID="lblTest" runat="server" /> 
    </form> 
</body> 
</html> 
+0

+1:很好的例子 –

相關問題