Can I set DataGridView color using variable?

BugMan

Well-known member
Joined
Dec 27, 2010
Messages
52
Location
Tallahassee FL
Programming Experience
10+
I want to be able to set the color of a DGV cell based upon a choice by the user. Assume the user has a list to choose from:

Aqua
Azure
Beige
Bisque
Black
Coral
Plum
Tomato
etc. to about 20 colors.

I want to set the color of the cell using the users selection. Ideally, it would look something like this:



VB.NET:
        Dim dummy as string

        'get color from list selection
        dummy = "Coral"

        DataGridView1.Rows(0).Cells(1).Style.BackColor = Color. & dummy


Of course, this doesn't work. Is there a way to set the color using a variable? Right now I have a bunch of Select Case lines, but it seems very inefficient.

Surely there is a way. thanks in advance.
 
Assuming that your strings are actual Color names, i.e. they match the names of members of the KnownColor enumeration, you can use Color.FromName to generate a Color value to assign to your property.
 
Assuming that your strings are actual Color names, i.e. they match the names of members of the KnownColor enumeration, you can use Color.FromName to generate a Color value to assign to your property.

Sounds promising. The list that the user chooses from will indeed be the known color names. But how do you assign the color to .FromName? Can you show an example of the code? I've searched for this at length and find very little. Thanks jm!
 
OK, finally found something.... this seems to work nicely, but if there's a better way I'm all ears. Thanks again jm, you got me on the right track.

VB.NET:
Dim SelectedColor As System.Drawing.Color
Dim UserPickedColor As String

UserPickedColor = "Plum"


SelectedColor = System.Drawing.Color.FromName(UserPickedColor)


DataGridView1.Rows(0).Cells(0).Style.BackColor = SelectedColor
 
I would assume that your colour names would be in a ComboBox or the like. In that case, the code can be simplified to:
VB.NET:
DataGridView1.Rows(0).Cells(0).Style.BackColor = Color.FromName(ComboBox1.Text)
 
OK, finally found something.... this seems to work nicely, but if there's a better way I'm all ears. Thanks again jm, you got me on the right track.

VB.NET:
Dim SelectedColor As System.Drawing.Color
Dim UserPickedColor As String

UserPickedColor = "Plum"


SelectedColor = System.Drawing.Color.FromName(UserPickedColor)


DataGridView1.Rows(0).Cells(0).Style.BackColor = SelectedColor


It's probably too complicated to explain the reasoning, but it will suffice to say that the user selects a cell in the grid, then right clicks & chooses the color from a context menu that I have preloaded with about 20 colors. So, then I get the name of the menu item clicked, and use the FromName to set that color.

It'd be better, though, instead of displaying a context menu of colors, to display a color picker, or palette of colors and let the user pick from there. This is a new can of worms, but I'd sure like to see if that's possible if it's not too hard. Your thoughts?

Thanks again, awesome good help!
 
It certainly is possible. The ColorDialog exists for this very purpose. You create an instance, set the Color property to the current BackColor, display the dialogue and, if the user clicks OK, you get the new value of the Color property and assign it back to your BackColor. It's six lines of code.
 
It certainly is possible. The ColorDialog exists for this very purpose. You create an instance, set the Color property to the current BackColor, display the dialogue and, if the user clicks OK, you get the new value of the Color property and assign it back to your BackColor. It's six lines of code.

Wow. Embarrassingly easy. Can't believe I didn't try that first, before the context menu.

However, now I'd like to take it just one step further and put the actual name of the color into the cell as well. How can I get the name of the color selected from ColorDialog1?

VB.NET:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ColorDialog1.Color = DataGridView1.Rows(0).Cells(0).Style.BackColor
        If ColorDialog1.ShowDialog() = DialogResult.OK Then
            DataGridView1.Rows(0).Cells(0).Style.BackColor = ColorDialog1.Color

            [COLOR="seagreen"]'now, put the name of the color into the cell (This doesn't work, of course, so what's the right syntax?)[/COLOR]
            [COLOR="red"]DataGridView1.Rows(0).Cells(0).Value = System.Drawing.Color.FromName(ColorDialog1.Color)[/COLOR]
        End If
    End Sub
End Class

Thanks for your quick and valuable help, jmcilhinney!
 
Last edited:
Some progress. Evidently the Color Dialog box will return both verbal colors ("Red", "Olive", etc.) AND hexidecimal (?) colors like "ff808040"

If it's a verbal color name, the code below works, but it won't work with the hex color. Any way to capture both? The value needs to be stored by writing it to disk, and reread so that the color can be remembered next time the user runs the program.

VB.NET:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim SelectedColor As System.Drawing.Color
        Dim UserPickedColor As String

        ColorDialog1.Color = DataGridView1.Rows(0).Cells(0).Style.BackColor

        If ColorDialog1.ShowDialog() = DialogResult.OK Then
            DataGridView1.Rows(0).Cells(0).Style.BackColor = ColorDialog1.Color
            DataGridView1.Rows(0).Cells(0).Value = ColorDialog1.Color.Name
            UserPickedColor = ColorDialog1.Color.Name


            'write ColorDialog1.Color.Name to disk, to be read later so cell can retain user picked color
            'pretend we just read it from disk, called it UserPickedColor

            UserPickedColor = ColorDialog1.Color.Name

            'get the name, set the cell background color and add the text
            SelectedColor = System.Drawing.Color.FromName(UserPickedColor)

            'this does not work, backcolor is not displayed
            DataGridView1.Rows(0).Cells(1).Style.BackColor = SelectedColor

            ' this does work writing color name into cell
            DataGridView1.Rows(0).Cells(1).Value = UserPickedColor

            'this works if the color name is verbal ("red", "blue", "olive") but not if it comes from the 
            'color dialog box like "ff808040"


        End If
    End Sub
End Class
 
This actually has nothing to do with the ColorDialog. That behaviour belongs to the Color structure itself. A Color only has a friendly name if it corresponds to a KnownColor. There isn't a name for every possible shade. Once you have a Color value, you can test its IsNamedColor property and, if that's True, get a Friendly name from the Name property. If IsNamedColor is False then there's no name.
 
This actually has nothing to do with the ColorDialog. That behaviour belongs to the Color structure itself. A Color only has a friendly name if it corresponds to a KnownColor. There isn't a name for every possible shade. Once you have a Color value, you can test its IsNamedColor property and, if that's True, get a Friendly name from the Name property. If IsNamedColor is False then there's no name.

So does this mean that I can't pick a color from the dialog, save the name to disk, and use that name whatever it is to assign the color of a new cell in the future? If that's the case, I'll need to stick to the context menu after all. Thanks again!
 
Like I said, if it's a named colour then it has a name and if it's not a named colour then it doesn't have a name. You can save the hexadecimal RGB string and use that to later reconstruct the Color if it doesn't have a name, but you obviously can't use FromName to do it.
 
Like I said, if it's a named colour then it has a name and if it's not a named colour then it doesn't have a name. You can save the hexadecimal RGB string and use that to later reconstruct the Color if it doesn't have a name, but you obviously can't use FromName to do it.

How do you reconstruct the color from the hex RGB string? I don't care if I have the name or not, I just would like to be able to save the string and use it later. Thanks again.
 
The Color structure has FromArgb and ToArgb methods that will convert between a Color and an Integer representing the A, R, G and B components. You can store just that number somewhere if you like or, if you want a hexadecimal string, you can use myInteger.ToString("X8") and Convert.ToInt32(myString, 16).
 
The Color structure has FromArgb and ToArgb methods that will convert between a Color and an Integer representing the A, R, G and B components. You can store just that number somewhere if you like or, if you want a hexadecimal string, you can use myInteger.ToString("X8") and Convert.ToInt32(myString, 16).

OK, will try to figure out how to do that. Thanks very much.
 
Back
Top