10/05/2011

How To : HyperLink Column in SPGridView for SharePoint 2010

Below is the code :

 

using System;

using System.ComponentModel;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using System.Data;

 

namespace VisualWebPartProject5.VisualWebPart1

{

[ToolboxItemAttribute(false)]

public class VisualWebPart1 : WebPart

{

protected override void CreateChildControls()

{

GridView gview = new GridView();

SPList list = SPContext.Current.Web.Lists["Projects"];

SPQuery query = new SPQuery();

 

query.Query = "<OrderBy><FieldRef Name=\"Project\" Ascending=\"True\"/></OrderBy>";

 

query.ViewFields = "<FieldRef Name=\"Project\" Nullable=\"TRUE\" /><FieldRef Name=\"Client\" Nullable=\"TRUE\" /><FieldRef Name=\"URL\"

 

Nullable=\"TRUE\" />";

 

query.ViewFieldsOnly = true;

 

SPListItemCollection lic = list.GetItems(query);

 

DataTable dt = lic.GetDataTable();

 

dt.Columns.Add("Temp", typeof(string));

 

foreach (DataRow r in dt.Rows)

{

r["Temp"] = r["URL"];

}

 

gview.DataSource = dt;

 

HyperLinkField linkField = new HyperLinkField();

linkField.HeaderText = "Text";

linkField.DataTextField = "Project";

linkField.DataNavigateUrlFields =new string[] { "Temp"};

linkField.Target = "_blank";

gview.Columns.Add(linkField);

gview.DataBind();

this.Controls.Add(gview);

 

}

}

}

 

2 comments:

  1. Hello Naimish,

    Thanks for the details. I was trying to implement the above and I wanted to have one of the columns to show an image. The image will be something like PDF icon and will be the same for all rows. Can you suggest how to do it? I tried the hyperlink method and it is working and want to try the same for image. thanks.

    ReplyDelete
  2. Hi Naimish,
    Very well described. Also you can find a way here

    Thanks
    Bijay
    http://www.enjoysharepoint.com
    http://www.fewlines4biju.com

    ReplyDelete