2017-05-07 99 views
0

我會保持簡短 我是一名12年級的軟件工程學生,作爲我決定製作網站的最終項目。網站的內容並不重要。問題是這樣的:在GridView的TemplateField中獲取文本框的值

在附圖中有一個文本框內的gridview裏面的templatefield。我需要獲得用戶在裏面寫入的價值。在您輸入值後,按購買。我看過類似的問題,但都沒有提供可行的解決方案。這個值會消失。我用FindControl找到了正確的控件,但是值被刪除了。我怎麼知道我在正確的控制下?我去了客戶端,並添加到asp:TextBox以下: Text =「5」 這很好用,所以我知道它得到了正確的控制,但有些東西使它消失。我的gridview正在填充兩個數據集組合的數據集,我把合併命令和數據源和數據綁定都在if(!this.IsPostBack)。我完全失去了,不知道該怎麼做,非常感謝幫助。 The Picture of the Gridview

回答

0

通過使用FindControl搜索正確的行,可以訪問GridView中的所有控件。爲此,您可以將行號作爲CommandArgument發送,並在後面的代碼中使用。因此,首先使用OnCommand代替OnClick,並在aspx頁面上設置CommandArgument

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 

     <asp:Button ID="Button1" runat="server" Text="Purchase" OnCommand="Button1_Command" CommandArgument='<%# Container.DataItemIndex %>' /> 
    </ItemTemplate> 
</asp:TemplateField> 

然後在後面

代碼
protected void Button1_Command(object sender, CommandEventArgs e) 
{ 
    //get the rownumber from the command argument 
    int rowIndex = Convert.ToInt32(e.CommandArgument); 

    //find the textbox in the corrext row with findcontrol 
    TextBox tb = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox; 

    //get the value from the textbox 
    try 
    { 
     int numberOfTickets = Convert.ToInt32(tb.Text); 
    } 
    catch 
    { 
     //textbox is empty or not a number 
    } 
} 
相關問題