ASP.NET Add column to Gridview

二次信任 提交于 2019-12-24 05:08:26

问题


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://localhost/edit.aspx?ID=" + idOfRowItem.


回答1:


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.



来源:https://stackoverflow.com/questions/7521136/asp-net-add-column-to-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!