Seems to be easy but I am having a hard time with this.
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="id">
<ItemTemplate>
<a href="/visit.aspx?Id=<%#Eval("Id")%>" id="ID" name="ID"> <%#Eval("Id")%> </a>
</ItemTemplate>
</asp:TemplateField>
There is a button in the last column of gridview. Click this button updated the database and refreshed gridview. It also look at the id column in gridview and tries to highlight the row that was edited.
The code works without any problem if ID field is bounded field and is not a URL. But when it is a URL, I cannot seem to read the text value of the URL. I have tried various solution (help from SO and online)
HyperLink link = (HyperLink)row.FindControl("id"); // did not work
((HyperLink)GridView1.Rows[i].Cells[0].Controls[0]).Text // did not work
This is the code snippet that I need help with
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row;
row = GridView1.Rows[i];
if (row.RowType == DataControlRowType.DataRow)
{
HyperLink link = (HyperLink)row.FindControl("id");
if (((HyperLink)GridView1.Rows[i].Cells[0].Controls[0]).Text == button.CommandName)
{
row.BackColor = System.Drawing.Color.IndianRed;
}
}
}
I am using button.CommandName to store the ID field which works fine. I just can't seem to find the hyperlink control in the gridview inside a template field.
I am getting the following error which does not make sense to me
Unable to cast object of type 'System.Web.UI.DataBoundLiteralControl' to type 'System.Web.UI.WebControls.HyperLink'.
Update1 This code works without hitch, if I do not use hyperlink field.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row;
row = GridView1.Rows[i];
if (row.Cells[0].Text.Equals(button.CommandName))
{
row.BackColor = System.Drawing.Color.IndianRed;
}
}
If change the column 0 to hyperlink and change the code corresponding, then it does not work. Clearly reading the wrong cell is not the problem.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row;
row = GridView1.Rows[i];
HtmlAnchor anchor = (HtmlAnchor) row.Cells[0].Controls[0];
if ( anchor.InnerText.Equals(button.CommandName))
{
row.BackColor = System.Drawing.Color.IndianRed;
}
}