Nathan Cooley Nathan Cooley - 1 month ago 19
C# Question

How can I check if my color value is equal to Null

I need help trying to find if the selected color is null.

Because if I do not choose a color, I get an error

This is the code that I get the error with:

private void btnreturn_Click(object sender, RoutedEventArgs e)
{
int gettext;
int.TryParse(txtcount.Text, out gettext);

Color Colorpicker;

//this is where I am getting my error and I need to
//check to see if the selected colour is not null before taking its value
Colorpicker = (Color)colorpicker.SelectedColor;

MainWindow win2 = new MainWindow(gettext, Colorpicker);
win2.Show();
Close();
}

Answer

It seems that when you don't select a color from the colorpicker, that the colorpicker.SelectedColor is null, and causing your error.


You can check for this in your code, like so:

private void btnreturn_Click(object sender, RoutedEventArgs e)
{
    int gettext;
    int.TryParse(txtcount.Text, out gettext);

    Color Colorpicker; 

    // Check if the SelectedColor is not null, and do stuff with it
    if (colorpicker.SelectedColor != null)
    {
        Colorpicker = (Color)colorpicker.SelectedColor;

        MainWindow win2 = new MainWindow(gettext, Colorpicker);
        win2.Show();
        Close();
    }
    else
    {
        // You didn't select a color... do something else
    }
}

Side-note: if you are using C#6, and you want to be sure that your colorpicker object is not null, in your if check - you can use colorpicker?.SelectedColor also. Note the use of the ? which checks that the underlying object is not null before checking its property.


I would also suggest naming your variables a little more clearly and meaningfully...

For example, your Color Colorpicker; variable declaration. Would it not be better suited to Color selectedColor;?

Hope this helps!

Comments