【问题标题】:How to change color in TemplateField using Eval如何使用 Eval 更改 TemplateField 中的颜色
【发布时间】:2013-01-26 06:38:06
【问题描述】:

我有一个包含许多 TemplateField 的 Gridview。
我想让我的 html 源代码中的每个 <td> 都等于我的数据库中保存的颜色
我尝试代码位于下方但不工作它在<td> 内给我一个<span> 标记,带有我的颜色但但不会出现在浏览器上

<asp:TemplateField HeaderText="BackGround Color">
     <ItemTemplate>
           <asp:Label  ID="lblBackColor" runat="server" 
                   BackColor='<%# ConvertFromHexToColor( Eval("BackColor").ToString()) %>'>
            </asp:Label>
           <itemstyle width="20%" horizontalalign="Center" />
     </ItemTemplate>    
</asp:TemplateField>

C# 代码工作

public  Color ConvertFromHexToColor(string hex)
{
    string colorcode = hex;
    int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
    Color clr = Color.FromArgb(argb);
    return clr;
}

这是我浏览器中的源 html 和 css 代码

            <td>
                <span id="BodyZone__ThemesGrid_lblForeColor_0"  style="background-color: #FFFFFF;"></span>
                <itemstyle width="20%" horizontalalign="Center">
                    </itemstyle>
            </td>

CSS

table.activity_datatable td {
padding: 8px 15px;
color: #6c6c6c;
vertical-align: middle;
-webkit-transition: all 0.2s;
}

【问题讨论】:

  • span中没有文字所以backgroupnd中没有颜色
  • 你说的every td是什么意思
  • 是 HTML 中的标准表格数据标签。

标签: asp.net html css gridview


【解决方案1】:

您需要在标签内放置文本(呈现为跨度)

<asp:TemplateField HeaderText="BackGround Color">
  <ItemTemplate>
    <asp:Label  ID="lblBackColor" runat="server" BackColor='<%# ConvertFromHexToColor( Eval("BackColor").ToString()) %>'>PUT_TEXT_HERE</asp:Label>
    <itemstyle width="20%" horizontalalign="Center" />
  </ItemTemplate>
</asp:TemplateField>

您可能还更喜欢使用面板(呈现为 div)而不是标签。不要忘记将东西放在 div 或 span 中。

【讨论】:

    【解决方案2】:
    ForeColor='<%# Convert.ToString(Eval("ESM")) == "Elective" ? System.Drawing.Color.Green: 
               Convert.ToString(Eval("ESM")) == "Emergency" ? System.Drawing.Color.Red: System.Drawing.Color.Purple%>'
    

    试试这个代码............

    【讨论】:

      【解决方案3】:

      如果你想用一个布尔值检查它是否为真,那么绿色会起作用,否则红色会起作用。然后根据 Eval 函数显示具有相应颜色的文本。这里 GetStatus 是一个你需要在代码中创建它的方法,我们将文本绑定到 UI,否则你可以像往常一样使用 Eval 或 Bind 函数进行绑定。

       ForeColor='<%# (bool)Eval("UserType")==true?System.Drawing.Color.Green:System.Drawing.Color.Red %>'
                                      Text='<%# GetStatus((bool)Eval("UserType")) %>'>
      

      【讨论】:

        猜你喜欢
        • 2017-11-03
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        相关资源
        最近更新 更多