填充数据库中的颜色

时间:2009-09-18 10:04:03

标签: c# asp.net

我的数据库中有颜色表。页面加载颜色时,颜色名称和颜色应显示在GridView中。

datafield =“color_Id”包含十六进制颜色值。我想将该十六进制颜色代码用于gridview表的背面颜色。

我的代码是:

<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>

3 个答案:

答案 0 :(得分:1)

在eval之前放一个#就像这样。应该工作。

BackColor='#<%# Eval("color_Id") %>'

答案 1 :(得分:0)

BackColor是System.Drawing.Color属性,而不是字符串属性。我不确定ASP.NET使用什么来转换BackColor =“#FF00FF”,但是在运行时评估字符串时它不起作用。

在您的代码中使用以下内容:

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

答案 2 :(得分:0)

我是通过引用代码完成的。

感谢你对杰森的一点点了解。

这些是代码

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>
                &nbsp;<asp:TextBox ID="txtColor" runat="server" Enabled="False"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </columns>
</asp:GridView>

谢谢你的观点&amp;帮助我解决问题。