您的问题分为三个部分:
- 如何在GridView中添加DropDownList?
- 如何从 GridView 中的 DropDownList 中获取选中项?
- 如何计算数值并在GridView中显示?
我们可以这样做。首先在页面中添加此标记。我为产品名称添加了一列以使其看起来更好:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="ddlQuantity" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" Text='<%#Eval("Price") %>' runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblAmount" Text="0.00" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
如何在GridView中添加DropDownList
在 Page_Load() 中填充 GridView(我使用了产品列表):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Test data to populate GridView
GridView1.DataSource = new List<Product>()
{
new Product{ID=1, Name="Paper", Price=7.99M},
new Product{ID=2, Name="Pen", Price=14.99M},
new Product{ID=3, Name="Pencil", Price=1.99M}
};
GridView1.DataBind();
}
}
这将触发GridView 的RowDataBound 事件。在事件方法中,我们将在每一行中绑定 DropDownList,如下所示:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = e.Row.FindControl("ddlQuantity") as DropDownList;
if (ddl != null)
{
ddl.DataSource = new List<string>() { "0", "1", "2", "3", "4" };
ddl.DataBind();
}
}
}
如何从 GridView 内的 DropDownList 中获取所选项目和
如何计算数值并在GridView中显示
当您更改 DropDownList 中的任何选择时,将触发其 SelectedIndexChange 事件。在那个事件方法中,我们可以找到哪个 DropDownList 发生了变化,它也是“NamingContainer”——GridView 的行包含它:
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = ((DropDownList)sender).NamingContainer as GridViewRow ;
if (gvr != null)
{
decimal price = 0.00M;
int quantity = 0;
//We can find all the controls in this row and do operations on them
var ddlQuantity = gvr.FindControl("ddlQuantity") as DropDownList;
var lblPrice = gvr.FindControl("lblPrice") as Label;
var lblAmount = gvr.FindControl("lblAmount") as Label;
if (ddlQuantity != null && lblPrice != null && lblAmount != null)
{
int.TryParse(ddlQuantity.SelectedValue, out quantity);
decimal.TryParse(lblPrice.Text, out price);
lblAmount.Text = (price * quantity).ToString();
}
}
}
结果如下:
您可以下载测试项目here。