2011-07-05 73 views
0

說我有一個在ItemTemplate一個TextBox控件ListView控件:獲取價值,對錶單提交

<asp:ListView ID="aspectsAndRatings" runat="server"> 
    <LayoutTemplate> 
     <ul> 
      <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> 
     </ul> 
    </LayoutTemplate> 
    <ItemTemplate> 
     <li> 
      <asp:TextBox ID="rating" runat="server" /> 
     </li> 
    </ItemTemplate> 
</asp:ListView> 

當這種形式被髮布(點擊提交按鈕)我想提取已經輸入到文本框中的值。

我當然可以,只要做到以下幾點:

Request.Form["ctl00$MainContent$aspectsAndRatings$ctrl0$rating"] 

但我敢肯定,ASP.NET提供了一個更清潔的方式來獲得進入的值,爲ListView的每一行。我只是不記得它是什麼。

(我曾嘗試listView.Items [N] .FindControl(「等級」),但它有一個空值返回文本框,而不是用戶輸入的值。)

回答

2

您應該能夠在回發處理程序中使用下面的代碼獲取值。只要記住不要在頁面加載事件中重新綁定你的中繼器。

foreach (var item in aspectsAndRatings.Items) 
{ 
    TextBox textBox = item.FindControl("rating") as TextBox; 
    if (textBox != null) 
    { 
     string textValue = textBox.Text; 
    } 
} 
+1

這是我會做的,但是,它可能值得使用'as'關鍵字並首先檢查'null'的項目。 TextBox textBox = item.FindControl(「rating」)as TextBox;'然後if(textBox!= null){string textValue = textBox.Text;因爲我相信這個解決方案更快更安全。 – simonlchilds

+0

@csharpsi恩說。按照你的建議編輯答案。謝謝。 –