The quantity (the quantity added to the database) in the text field is loaded by the Eval () method from the basket basket table. What I want to achieve is that when I change the quantity manually and click update, the quantity for this record will be updated and then the grid will be reloaded. It seems I can not get the value of this text field in the code.
I know the FindControl () method, which is used to get the value from the controls in the itemtemplate, but I don’t know how to use it here.
Awakened below, but always gets a nullReferenceException
TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted"); int _quantity = Convert.ToInt16(txt.Text);
Note: there is a button, but does nothing.

<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 # code:
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(); } }
source share