Thursday, August 20, 2009

Formatting columns inside gridview using codebehind helper function

Formatting columns inside gridview: There is more power with the server tags '' you can call codebehind functions from inside there eg:

<asp:GridView ID="GV" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="title" /> <asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblnumber" runat="server"
Text='<%# FormatThis(Eval("title")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

In code behind:
public string FormatThis(object value)
{
return "This is my formatted string: " + str ;
}

In the above code the value passed by the Eval function comes as object, we dont know the type at compile time. So we need to cast as the type that we know is coming in. I prefer this approach over the overriding the databinding events and modifying the value of cells with column names, yuck!

No comments:

Post a Comment