4

文本框中的数量(DB 中的数量)是通过 Basket DB 表中的 Eval() 方法加载的。我想要实现的是,当我手动更改数量并单击更新时,该记录的数量将被更新,然后网格将被重新加载。我似乎无法在后面的代码中检索该文本框的值。

我知道 FindControl() 方法用于从 itemtemplate 中的控件获取值,但我不知道如何在这里使用它。

下面的尝试但总是得到 nullReferenceException

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

注意:按钮在那里,但什么也不做。

在此处输入图像描述

<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

3 回答 3

4

使用 GridView.Rows 集合来查找控件。您可以在行集合索引器中传递行的索引。

TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
于 2013-03-13T12:19:46.273 回答
3

您还必须传递行索引,您的代码将如下所示

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

我希望它对你有用。

于 2013-03-13T12:21:38.073 回答
2
  Control ctrl = e.CommandSource as Control;  

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

       TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted"); 
   }
于 2013-03-13T12:24:51.477 回答