2013-03-13 164 views
4

通過購物籃數據庫表中的Eval()方法加載文本框中的數量(數量在數據庫中)。我想要實現的是當我手動更改數量並單擊更新時,該記錄的數量將被更新,然後網格將被重新加載。我似乎無法在後面的代碼中檢索該文本框的值。無法從項目模板中的文本框中獲取文本框的值

我知道FindControl()方法是用來從itemtemplate中的控件獲取值,但我不知道如何在這裏使用它。

下面的嘗試,但總是得到的NullReferenceException

TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted"); 
int _quantity = Convert.ToInt16(txt.Text); 

注:按鈕是有,但什麼都不做。

enter image description here

<ItemTemplate>   
    <asp:TextBox runat="server" ID="txtQuantityWanted" Text='<%# Eval("quantityWanted") %>' ></asp:TextBox> 
    <asp:LinkButton ID="LinkButton11" runat="server" CommandName="update" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Update</asp:LinkButton> 
    <asp:Button ID="Button21" runat="server" Text="Button" CommandName="edit" /> 
</ItemTemplate> 

<asp:TemplateField HeaderText="Total [£]"> 
    <ItemTemplate> 
     <asp:Label id="lblItemTotal" runat="server" Text='<%# String.Format("{0:C}", Convert.ToInt32(Eval("quantityWanted"))* Convert.ToDouble(Eval("price"))) %>' ></asp:Label> 
     <asp:LinkButton ID="LinkButton1" runat="server" CommandName="remove" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Remove</asp:LinkButton> 
    </ItemTemplate> 
</asp:TemplateField> 

C#代碼:

protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    // ..... 
    else if (e.CommandName == "update") 
    { 
     string params = Convert.ToString(e.CommandArgument); 
     string[] arg = new string[2]; 
     arg = params.Split(';'); 
     name = Convert.ToString(arg[0]); 
     datetimeAdded = Convert.ToString(arg[1]); 

     const string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=L:\ASP.NET\Exercise1\Exercise1\Exercise1\App_Data\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"; 

     DataSet ds = new DataSet("Employees"); 
     SqlConnection connection = new SqlConnection(strConn); 

     // Here I need value from textbox to replace 11 
     SqlCommand abc = new SqlCommand("UPDATE Basket SET quantityWanted = 11 WHERE coffeeName LIKE '%" + name + "%' AND datetimeAdded LIKE '" + datetimeAdded + "' ", connection); 
     connection.Open(); 
     int ii = abc.ExecuteNonQuery(); 
     connection.Close(); 
    } 
} 

回答

4

使用GridView.Rows收集找到控制。您可以在行集合索引器中傳遞行的索引。

TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted"); 
+0

我喜歡它!回答小時的挫折=單行代碼......在5分鐘內接受 – johnyTee 2013-03-13 12:27:00

+0

這很好,如果它的工作,謝謝。 – Adil 2013-03-13 12:30:34

3

你必須通過行索引,以及,你的代碼看起來像這樣

TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted"); 

我希望它會爲你工作。

+0

+1正確的答案,thx – johnyTee 2013-03-13 12:28:30

+0

你的歡迎... – Rahul 2013-03-13 12:51:10

2
Control ctrl = e.CommandSource as Control; 

    if (ctrl != null)  
    {  
     GridViewRow gvRow = ctrl.Parent.NamingContainer as GridViewRow;  

     TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted"); 
    } 
+1

+1這個答案節省我手動獲取行索引,這是偉大的。 – johnyTee 2013-03-13 12:37:21