SharePoint: Using SPListItem in SPGridView Custom Template Columns

In the past, where I have had to create custom columns for use in an SPGridView, I have created a class that implements ITemplate and have then got data from the datasource in the appropriate databinding event handler using

string itemId = DataBinder.GetPropertyValue(currentGridViewRow.DataItem, “ID”).ToString();

I recently came accross another way of doing it that allows you to access an SPListItem directly (although this only works if you are binding your SPGridView to an SPDataSource). The code below illustrates:

public class LabelTemplate : ITemplate
{
    void ITemplate.InstantiateIn(Control container)
    {
        Label label = new Label();
        container.Controls.Add(label);
        label.DataBinding += new EventHandler(this.Label_DataBinding);
    }

    private void Label_DataBinding(object sender, EventArgs e)
    {
        Label test = (Label)sender;
        // Get SPListItem
        SPGridViewRow currentRow = (SPGridViewRow)test.NamingContainer;
        SPDataSourceViewResultItem currentItem = (SPDataSourceViewResultItem)currentRow.DataItem;
        SPListItem item = (SPListItem)currentItem.ResultItem;
        test.Text = item.Title;
    }
}

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.