I have a gridview displaying data on a Webpart, with linkbuttons within the header to allow sorting by different fields (with a custom sorting method which will be different for each column)
The button works fine but within the click handler it changes the text, command name and font.
This never works (i.e. no changes take place on the button), is there any reason it shouldn’t work?
Gridview ASCX:
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false"
AllowSorting="False">
<HeaderStyle />
<RowStyle />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<table>
<tr>
<td>
<a>Name</a>
<asp:LinkButton ID="btnNameSort" runat="server" Text="Sort Ascending" OnClick="btnNameSort_Click" CommandName="asc" />
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
... Item code
</ItemTemplate>
This is the code behind:
public void btnNameSort_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)GridView1.HeaderRow.FindControl("btnNameSort");
if (btn.CommandName == "asc")
{
btn.Text = "Sort Descending";
btn.Font.Bold = true;
btn.CommandName = "desc";
updateGridView1(true, "title");
}
else
{
btn.Text = "Sort Ascending";
updateGridView1(false, "title");
}
I think the GridView is being re-rendered and those changes you made don’t stick. My guess is there is a DataBind Method in updateGridView.. right? I think you should set the text by storing the sort the direction and sort column in ViewState properties. When the GridView is rebound, you can access those properties, which will now be persistent.
BTW– I think this is a really good question. You can also subscribe to the ItemCreated handler and grab the header. If your sortdirection is stored in the viewstate and your sortcolumn is stored in the viewstate, you can find the cell you are looking for and adjust it accordingly.