我正在开发一个电子商务应用程序,问题在于显示购买的商品数量。DropDownList 显示更改数量的选项,它位于网格视图中,并且具有 selectedindexchanged 事件。事件代码工作正常,但是当有两个(或更多)产品并且我们更改一行的数量然后更改其他行的数量时,前一行数量设置回默认值“1”,而总价列显示我们设置到 DropDownList 的价格和数量的乘积。
我的下拉列表代码:
<asp:TemplateField HeaderText="Qty">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlQty" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlQty_SelectedIndexChanged">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
我的 SelectedIndexChanged 和 GridView RowDataBoundevent 的 C# 代码:
protected void ddlQty_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlQty =(DropDownList)sender;
int rowindex = int.Parse(ddlQty.Attributes["rowindex"].ToString());
ViewState["index"] = rowindex;
ViewState["I"] = ddlQty.SelectedValue;
decimal price = Convert.ToDecimal(ds.Tables[0].Rows[rowindex]["Price"].ToString());
decimal totalprice = price * Convert.ToInt32(ddlQty.SelectedValue);
ds.Tables[0].Rows[rowindex]["TotalPrice"] = totalprice;
GridView1.DataSource = ds;
GridView1.DataBind();
ds.Tables[1].Rows[0]["TotalPrice"] = decimal.Parse(ds.Tables[1].Rows[0]["TotalPrice"].ToString()) + totalprice - Convert.ToDecimal(ds.Tables[0].Rows[rowindex]["Price"].ToString());
GridView1.FooterRow.Cells[2].Text = "Total Amount =";
GridView1.FooterRow.Cells[3].Text = ds.Tables[1].Rows[0]["TotalPrice"].ToString();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlQty");
ddl.Attributes.Add("rowindex", e.Row.RowIndex.ToString());
if (ViewState["index"] != null)
{
if (e.Row.RowIndex.ToString() == ViewState["index"].ToString())
{
ddl.SelectedValue = ViewState["I"].ToString();
}
}
}
}
我还附上了一张图片以使其更清晰。