无法从itemtemplate中的文本框中获取文本框值

时间:2013-03-13 12:17:39

标签: c# asp.net

文本框中的数量(以DB为单位的QuantityWan)是通过Basket DB表中的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();
    }
}

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

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

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

我希望它对你有用。

答案 2 :(得分:2)

  Control ctrl = e.CommandSource as Control;  

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

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