I generate the columns for my RadGrid in code behind. I do this by creating a DataTable from a stored procedure and then binding the DataTable to the RadGrid. I now want to display a graphic in certain columns based in the information in that cell. I normally do it in the .aspx code like this:
I can't seem to figure out how to do this in code behind. I can add an image to the column, but it is the same image for all cells in the column. I don't know where to add code (in the column definition) that changes the image based on the value of the cell. Here is how I create the column and add an image which is the same for all cells.
I have thought of adding the rows to the RadGrid one at a time, but I would rather define the column and then just bind the RadGrid to the DataTable. I also want to select between more than two images, so the "Visable = (bool)Eval" in the first example is not sufficient, but I figure I can change a given solution to work how I want it.
<
telerik:GridTemplateColumn
DataField
=
"State"
DataType
=
"System.Boolean"
FilterControlAltText
=
"Filter Public column"
HeaderText
=
"State"
SortExpression
=
"State"
UniqueName
=
"State"
>
<
ItemTemplate
>
<
asp:Image
ID
=
"Image1"
ImageUrl
=
"~/images/true.png"
Visible='<%# (bool)Eval("State") == true %>' runat="server" />
<
asp:Image
ID
=
"Image2"
ImageUrl
=
"~/images/false.png"
Visible='<%# (bool)Eval("State") == false %>' runat="server" />
</
ItemTemplate
>
</
telerikf:GridTemplateColumn
>
string
templateColumnName = dc.ColumnName;
GridTemplateColumn templateColumn =
new
GridTemplateColumn();
templateColumn.ItemTemplate =
new
MyItemTemplate(templateColumnName);
templateColumn.HeaderText = templateColumnName;
templateColumn.DataField = dc.ColumnName;
this
.RadGrid1.MasterTableView.Columns.Add(templateColumn);
private
class
MyItemTemplate : ITemplate
{
protected
Image myimage;
private
string
colname;
public
MyItemTemplate(
string
cName)
{
colname = cName;
}
public
void
InstantiateIn(System.Web.UI.Control container)
{
myimage =
new
Image();
myimage.ImageUrl =
""
;
// Setting an image here works, but is the same for all cells
myimage.ID =
"templateColumnImage"
;
container.Controls.Add(myimage);
}
}
I have thought of adding the rows to the RadGrid one at a time, but I would rather define the column and then just bind the RadGrid to the DataTable. I also want to select between more than two images, so the "Visable = (bool)Eval" in the first example is not sufficient, but I figure I can change a given solution to work how I want it.