簡體   English   中英

無法從itemtemplate中的文本框中獲取文本框值

[英]Cannot get textbox value from textbox in itemtemplate

文本框中的數量(dataWanted in 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();
    }
}

使用GridView.Rows集合來查找控件。 您可以傳遞行集合索引器中的行索引。

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

您也必須傳遞行索引,您的代碼將如下所示

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

我希望它對你有用。

  Control ctrl = e.CommandSource as Control;  

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM