Reputation: 320
I have a gridview in my page that I have to set from the code behind (certain columns are not included sometimes), but one column contains hyperlinks. I am currently setting the gridview and hyperlink column in the .aspx page like this:
<asp:GridView runat="server" ID="GridView1" >
<Columns>
<asp:BoundField DataField="Edit" HtmlEncode="false" HeaderText="" HeaderStyle-Wrap="false" SortExpression="Edit" />
</Columns>
</asp:GridView>
I'm binding the rest of the data in the code behind:
GridView1.DataSource = dt;
GridView1.DataBind();
Page.DataBind();
The link column is showing up fine, and the links work as expected. However, the GridView that is created has the link column on the left, all of the columns that I want to show up, and then another column on the right that contains a string of the link, like this:
<a href='ForecastComments.aspx?zip=49905&date=1day'>Edit
Is there a way I can get rid of this column but still have my link column? I can't delete it from the table because I need access to it for the link column. I tried changing the code behind to this:
GridView1.DataSource = dt;
GridView1.DataBind();
this.GridView1.Columns[12].Visible = false;
Page.DataBind();
because the column I don't want showing is column 12, but the number of columns in the gridview is apparently only 1 (not sure why that is), so anyway, it didn't work. Bonus: I would rather have the link column on the right of the table, not the left--if anyone knows how to do that also, that'd be awesome.
Upvotes: 0
Views: 3261
Reputation: 73791
The cells can be moved and/or deleted in the RowDataBound
event of the GridView. You can set the event handler in the markup:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
In code-behind, you define a variable to hold the index of the link column that you want to remove:
private int LinkColIndex;
and get its value from the DataTable before binding the data to the GridView:
LinkColIndex = dt.Columns["Edit"].Ordinal;
GridView1.DataSource = dt;
GridView1.DataBind();
Finally, you process the cells for each row in the RowDataBound
event handler:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell cell = e.Row.Cells[0];
e.Row.Cells.RemoveAt(0);
e.Row.Cells.RemoveAt(LinkColIndex);
e.Row.Cells.Add(cell);
}
Upvotes: 2