ASP.NET将列添加到Gridview

时间:2011-09-22 20:33:53

标签: c# asp.net gridview

我有一个gridview,它使用LINQ to SQL显示数据库中的数据。

AssetDataContext db = new AssetDataContext();
equipmentGrid.DataSource = db.equipments.OrderBy(n => n.EQCN);

我需要在girdview的末尾添加一个列,该列将包含编辑/删除/查看行的链接。我需要链接为“http://localhost/edit.aspx?ID =”+ idOfRowItem。

1 个答案:

答案 0 :(得分:3)

尝试将GridField添加到GridView中,如下所示:

<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <a href="http://localhost/edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "id") %>">Edit</a>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

在项目模板中,您可以放置​​您喜欢的任何链接,并将您希望的任何数据从DataSource绑定到它们。在上面的示例中,我刚刚从名为id的列中提取了值。

根据情况,这可以正常工作,但是上面的列将在GridView中最左边对齐,右边是所有自动生成的列。

要解决此问题,您可以为RowCreated事件添加处理程序,并将列移动到自动生成列的右侧,如下所示:

gridView1.RowCreated += new GridViewRowEventHandler(gridView1_RowCreated);

...

void gridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    TableCell actionsCell = row.Cells[0];
    row.Cells.Remove(actionsCell);
    row.Cells.Add(actionsCell);
}

希望这有帮助。

相关问题