[RESOLVED] Setting Image Button URL in code behind
I thought this would be a simple issue, but I've been struggling. I created an image button in my header template. When clicked, it calls the Sorting method. When I change the image url in code behind, it does not render. By setting a break point, I can see the property being updated, but I assume it is getting overridden by the default I set in the HTML page.
Code:
<HeaderTemplate>
<span>Claim Id</span>
<asp:ImageButton ID="btnClaimIdSort" runat="server" ImageUrl="~/Styles/UpArrow.ico" OnClick="Sorting" ToolTip="ClaimId" />
</HeaderTemplate>
Code:
protected void Sorting(object sender, EventArgs e)
{
var sortButton = (ImageButton)sender;
// parse new sort
var newField = sortButton.ToolTip;
// parse existing sort
var existingSortArgs = this.ClaimSort.Split(' ');
var existingField = existingSortArgs[0];
var existingDirection = existingSortArgs[1];
if (string.Compare(newField, existingField,true) == 0)
{
// swap direction
var newDirection = (existingDirection == "Asc" ? "Desc" : "Asc");
sortButton.ImageUrl = (newDirection == "Asc" ? "~/Styles/DownArrow.ico" : "~/Styles/UpArrow.ico");
this.ClaimSort = string.Format("{0} {1}", existingField, newDirection);
}
else
{
sortButton.ImageUrl = "~/Styles/UpArrow.ico";
this.ClaimSort = string.Format("{0} Asc", newField);
}
// rebind data
this.BindResultsGrid();
}
Re: Setting Image Button URL in code behind
Hi,
Normally, the image doesn't get updated on your sorting event because you rebind your Gridview control with new datasource.
Hence, the control has been re-initialized.
Try updating the image url through your GridView RowDataBound event.
Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
ImageButton sortButton = (ImageButton)e.Row.FindControl("btnClaimIdSort");
//Modify code below with your logic.
if (sortButton != null)
{
if (sortdescription =="ASC")
{
sortButton.ImageUrl = "~/Styles/UpArrow.ico";
}
else
sortButton.ImageUrl = "~/Styles/DownArrow.ico";
}
}
}
KGC
Re: Setting Image Button URL in code behind
That makes total sense, and your solution works like a charm. Thank you.