KSwift87 KSwift87 - 8 days ago 6
Vb.net Question

How to set BackColor of a table cell dynamically with a database value?

As a bonus to the project I'm currently working on, the people would like it if I could change the background color of individual table cells depending on what their value is. So in the RadGrid_ItemDataBound event handler I have, I'm trying to set the BackColor of the cell if the cell's text equals a certain value from a dataset in my database. My current code is like so:

For i As Integer = 0 To ds2.Tables(0).Rows.Count - 1 Step 1
If tc.Text = ds2.Tables(0).Rows(i)("LookupValue") Then
tc.BackColor = ds2.Tables(0).Rows(i)("Ref1")
Exit For
End If
Next


The problem is when setting a color in the code-behind, I apparently have to set it to an object of System.Drawing.Color -- I can't just feed it a string value like I can in CSS. So in the code snippet I've posted above, my code throws a runtime exception on
tc.BackColor = ds2.Tables(0).Rows(i)("Ref1")
. I've also discovered that I can't use CType to change a string value into an equivalent object of System.Drawing.Color .

I've thought of a solution that I COULD use. I could create a custom object that has a Name property and a System.Drawing.Color property. I could instantiate several objects according to all color values available in the database and then compare the cell text against the objects' Name properties, however I fear doing this will be rather resource-intensive (and this application's performance is already taking a hit because it has to run under IE7).

So does anybody know of a way I could pull off what I need to here in a relatively simple, non-resource-intensive fashion?

Answer

Color.FromName() handing it the name in your database. There are also other methods like FromRGB, but FromName sounds like what you want.

http://msdn.microsoft.com/en-us/library/system.drawing.color.fromname.aspx