R – Itemtemplate to view Picture in Asp Datagrid (in code)

asp.netdatagriditemtemplate

I´m writing on a webpart for sharepoint, so I have to generate a Datagrid problematically.

The Situation is that I get a Dataview, generate the Gris and bind the Data.
One column should show a Image, so I have to generate a template column with item template.

So code looks like this:

//Instantiate the DataGrid, and set the DataSource
_grdResults = new DataGrid();
_grdResults.AutoGenerateColumns = false;
_grdResults.DataSource = view;
TemplateColumn colPic = new TemplateColumn();
colPic.HeaderText = "Image";

I found dozens of example for asp to create the item-template, but how construct one in code and bind it´s ImageUrl to "imgURL" of the Dataview?

thanks for any advice

Ren

Best Solution

You need to create a class that implements that ITemplate interface.

public class TemplateImplementation : ITemplate 
{ 
    public void InstantiateIn(Control container)
    {
        Image image = new Image();
        image.DataBinding += Image_DataBinding;
        container.Controls.Add(image); 
    }

    void Image_DataBinding(object sender, EventArgs e)
    {
        Image image = (Image)sender;
        object dataItem = DataBinder.GetDataItem(image.NamingContainer);
        // If the url is a property of the data item, you can use this syntax
        //image.ImageUrl = (string)DataBinder.Eval(dataItem, "ThePropertyName");
        // If the url is the data item then you can use this syntax
        image.ImageUrl = (string)dataItem;
    } 
}

You then set your ItemTemplate to an instance of this class.

colPic.ItemTemplate = new TemplateImplementation();
Related Question