SharePoint Dynamic Change Hyperlink field in Gridview
I am trying to answer questions on the SharePoint Forums and I saw a lot of questions regarding fields that are not updating.
What happens is they get only the first or last item in the hyperlink field in the gridview rows.
This because if you bound the field in the Create ChildControls it is bound to all rows.
So What do you need to do:
A little code snippet of the create child controls
//Ogrid is SpGridView
this.oGrid.ShowHeader = true;
this.oGrid.AutoGenerateColumns = false;
this.oGrid.CellPadding = 0;
this.oGrid.CellSpacing = 0;
this.oGrid.EnableViewState = true;
this.oGrid.RowDataBound += new GridViewRowEventHandler(oGrid_RowDataBound);
this.Controls.Add(this.oGrid);
//Set options and data on our gridview
this.oGrid.AllowSorting = true;
this.oGrid.AllowPaging = true;
this.oGrid.PagerTemplate = null;
this.oGrid.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler(oGrid_PageIndexChanging);
this.oGrid.Sorting += new GridViewSortEventHandler(oGrid_Sorting);
As you can see I add a new event
This event fires with every row while rendering:
Here You can implement your dynamic hyperlink
void oGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (System.Data.DataRowView)e.Row.DataItem;
e.Row.Cells[0].Text = string.Format(@"<a href=""\\{0}\{1}\{2}.doc"">{2}", PathToDoc, drv[5].ToString(), e.Row.Cells[0].Text, 1);
HyperLink lb = (HyperLink)e.Row.Cells[0].Controls[0];
lb.ToolTip = lb.NavigateUrl;
}
}
As you can see it is pretty easy to change text hyperlinks images etc in the RowDataBound event.
I know it is a short post but I hope it helps people to understand how to implement dynamic fields in the SharePoint GridView.