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


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!

3

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