Monday, June 25 2007: Funky Databinding to Control Properties
It's widely advertised that you can bind to any property of a control you'd care to. Getting it to actually work may be less than intuitive. This example binds the backcolor property of a label control based on color names stored in a database.
This ASPX code (note the Import statement at top of file):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="HourAvailability" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="HourAvailability" HeaderText="HourAvailability" ReadOnly="True"
SortExpression="HourAvailability" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="DisplayColor" SortExpression="DisplayColor">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=''>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" BackColor=''
Text=''>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString=""
SelectCommand="SELECT * FROM [TestingTable]">
</form>
</body>
</html>
Produces this table:
| HourAvailability | Description | DisplayColor |
|---|---|---|
| 0 | Unavailable | red |
| 1 | Can Work | yellow |
| 2 | Want to Work | green |
| 3 | Scheduled To Work | blue |
| 4 | Did Work | purple |