Reputation: 11
I have color table in my database. When page loads color id and color name and color should displayed in GridView.
datafield="color_Id" contains hex color value. I want to use that hex color code into the back color of the gridview table.
My code is:
<asp:GridView id="GridView1" runat="server" BorderColor="Black" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<columns>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:BoundField DataField="color_Id" HeaderText="Color Id"></asp:BoundField>
<asp:BoundField DataField="color" HeaderText="Color Name"></asp:BoundField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:Label ID="lblColor" BackColor='<%# Eval("color_Id") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
Upvotes: 0
Views: 1491
Reputation: 11
I done it by referencing codes.
thanks for give little idea for jason.
these are the codes
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string colId="",colr="";
colId = e.Row.Cells[1].Text;
colr = e.Row.Cells[2].Text;
if (colId.Trim() != "Color Id" && colr.Trim() != "Color Name")
{
TextBox t = (TextBox)e.Row.FindControl("txtColor");
if (t != null)
{
t.BackColor = System.Drawing.ColorTranslator.FromHtml(colId);
}
}
}
<asp:GridView id="GridView1" runat="server" BorderColor="Black" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" BackColor="Transparent">
<columns>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:BoundField DataField="color_Id" HeaderText="Color Id"></asp:BoundField>
<asp:BoundField DataField="color" HeaderText="Color Name"></asp:BoundField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:TextBox ID="txtColor" runat="server" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
thank you for view & give me a help to overcome my problem.
Upvotes: 0
Reputation: 8914
BackColor is a System.Drawing.Color property and not a string property. I'm not certain what magic ASP.NET uses to convert BackColor="#FF00FF", but it doesn't work when you evaluate the string at runtime.
Use the following in your code behind:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim c As Label = e.Row.FindControl("lblColor")
If c IsNot Nothing Then
c.BackColor = System.Drawing.Color.FromName(e.Row.DataItem.color_ID)
End If
End If
End Sub
Upvotes: 0
Reputation: 375
Just put an # before the eval like this. Should work.
BackColor='#<%# Eval("color_Id") %>'
Upvotes: 1