Search code examples
asp.netbackcolorpartial-postback

backcolor of a label lost on postback when using Eval to set it


I have a datalist in my website and each data item has a label with backcolor. The datasource is set and I have a label with backcolor which is set from a color Code in datasource :

<asp:DataList runat="server" ID="RptColor" DataSourceID="DSColor" RepeatDirection="Horizontal" RepeatLayout="Table">
    <ItemTemplate>
        <div class="col-md-1">
            <asp:Label runat="server" ID="RpLblColorCode" BackColor='<%# System.Drawing.Color.FromName(Eval("ColorCode").ToString()) %>' Width="20px" Height="20px"></asp:Label>
        </div>
    </ItemTemplate>
</asp:DataList>

the problem is that when I press a button and postback occurs the back color would be gone! ... I have an updatepanel on the page. please help me


Solution

  • Use ColorTranslator.FromHtml instead of Color.FromName. You can change your code to this:

    <asp:DataList runat="server" ID="RptColor" DataSourceID="DSColor" RepeatDirection="Horizontal" RepeatLayout="Table">
      <ItemTemplate>
         <asp:Label runat="server"
          ID="RpLblColorCode" BackColor='<%# System.Drawing.ColorTranslator.FromHtml(Eval("ColorCode").ToString()) %>'></asp:Label>
      </ItemTemplate>
    </asp:DataList>