在GridView中添加单元格

时间:2012-04-11 13:30:14

标签: c# asp.net

如何在gridview中的每一行的特定列中添加单元格,我想使用 RowCreated 事件。

我有gridview有3列(ProductName,Price,Count)我从数据库得到(ProductName,Price),我想为(count)添加值,ex:(Kitkat,2 $)我想添加数字5到(计数)列,我想在创建每一行时处理此操作。

由于

1 个答案:

答案 0 :(得分:2)

由于您尚未显示标记,我将假设(基于your comment)前两列为<BoundFields>。如果是这种情况,我会将第三列添加为<TemplateField>,在其中添加Label,然后使用RowDataBound事件将正确的数字添加到Label

以下是标记的样子:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:TemplateField HeaderText="Count">
            <ItemTemplate>
                <asp:Label ID="countLbl" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

代码隐藏:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Label countLbl = (Label)e.Row.FindControl("countLbl");
    //Your logic for what number to use should go here, I'm just defaulting to 5.
    countLbl.Text = "5";
}
相关问题