Use VALUE AS element color

Ok, I researched this as much as possible before I posted it, so I hope this is not a repost, but here goes ...

I made a datatable, let's say it has a coulmn called "cartype" then I added a column "color"

Ok, I linked the gridview, what I want to do is use the label and its FORECOLOR is the VALUE in the "color" column.

I've tried this:

<asp:BoundField DataField="cartype" HeaderText="Cars"  ItemStyle-Width="130" ItemStyle-ForeColor='<% Eval("Color") %>' />

      

but i got the error

"Unable to create an object of type System.drawing.color from its string representation '<% Eval (" color ")%>' for the ForeColor property.

I also tried adding a template field and got the same result.

I was trying not to use the rowdatabound event and use .Cells [3] because then when I add columns it is going to change the cell number and toggle everything! I was hoping I could make it cleaner by binding the color to the data.

+3


source to share


3 answers


Ok, I finished this. sadly: (

At the VERY END of my grid, I added an ASP: Hidden template field

<asp:TemplateField>
  <ItemTemplate>
   <asp:HiddenField ID="hColor" runat="server" Value='<%# Eval("Color") %>'/>
  </ItemTemplate>
</asp:TemplateField>

      



Then in RowDataBoundEvent I did this

Dim hid As HiddenField
hid = e.Row.FindControl("hColor")
If (hid.Value <> Nothing) Then
   e.Row.Cells(1).ForeColor = System.Drawing.ColorTranslator.FromHtml("#" + hid.Value)
End If

      

PS. I am the heart of C #. Don't like VB.NET. lol :)

+1


source


You tried:

 ForeColor='<%# System.Drawing.Color.FromName(Eval("Color")) %>'

      



?

+1


source


The reason for the error is that the runtime expects the ForeColor value to be a color, not a string. The runtime cannot create "Red" from the string "Red".

You can create a function in code using the following example to work around your problem. The function will take a string color value and return the system color. Also before filling the gridview, you can store the color column in an arraylist and use this arraylist to return the system color. Not the best way, but I can't think of anything else.

 ForeColor='<%# Convert.ToString(Eval("Color")) == "Blue" ? System.Drawing.Blue>

      

0


source







All Articles