开发者

ASP.NET Add column to Gridview

I have a gridview that is displaying data from a database using LINQ to SQL.

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

I need to add a column at the end of the girdview that will have links to edit/delete/view the row. I need the link to be "http://开发者_Go百科localhost/edit.aspx?ID=" + idOfRowItem.


Try adding a TemplateField to your GridView like so:

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

Within the item template you can place any links you like and bind any data you wish to them from your DataSource. In the example above I have just pulled the value from a column named id.

As things stand this would work fine, however the column above would be aligned left most in the GridView with all the auto generated columns to its right.

To fix this you can add a handler for the RowCreated event and move the column to the right of the auto generated columns like so:

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);
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜