通過購物籃數據庫表中的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();
}
}
我喜歡它!回答小時的挫折=單行代碼......在5分鐘內接受 – johnyTee 2013-03-13 12:27:00
這很好,如果它的工作,謝謝。 – Adil 2013-03-13 12:30:34