Adding Template Column to SPGridView

To create a template field such as Image in SPGridView, we need to create Templated Control inheriting from ITemplate. below is how this can be done:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
namespace SharePoint.Site.Search.Controls
    public class TemplatedImageControl:ITemplate
        private String _DataField;
        public TemplatedImageControl(String DataField)
            _DataField = DataField;
        public void InstantiateIn(Control container)
            Image img = new Image();
            img.DataBinding += new EventHandler(img_DataBinding);
        void img_DataBinding(object sender, EventArgs e)
            Image img = (Image)sender;
            SPGridViewRow container = (SPGridViewRow)img.NamingContainer;
            if (_DataField.Length > 0) {
                img.ImageUrl += DataBinder.Eval(container.DataItem, _DataField);
                img.Width = Unit.Pixel(16);
                img.Visible = true;
            else {
                img.Visible = false;

Now we can use this control in our SPGridView template column:

TemplateField typeColumn = new TemplateField();
typeColumn.HeaderText = "Type";
typeColumn.SortExpression = "Type";
//ImageUrl is a column name in datasource
typeColumn.ItemTemplate = new TemplatedImageControl("ImageUrl");

Once we are done with data binding and all, we have a solution to SPGridView with template column.


What did you think of this article?

  • No trackbacks exist for this post.
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.