Home > OS >  Textbox showing as null WPF
Textbox showing as null WPF

Time:10-12

I have 3 textboxes that a user can modify to change the RGB colors of certain colors of the window. What I'm doing to give them a visualization is have a box next to said textboxes that shows the color they're making with said RGB values in the textboxes. To do this, I set the TextChanged event for all 3 textboxes to a method that takes the text from the 3 textboxes, converts them to an integer with TryParse, assigns the numbers to a brush, then assigns the brush to the box so the user can see it. The XAML looks like this:

<TextBox Name="ColorPickerDisplayRed" Background="Transparent"
         BorderBrush="Transparent"
         FontFamily="Moon 2.0"
         Foreground="#6BAAFF"
         Text="255"
         TextAlignment="Center"
         Margin="0, -1.2, 0, 0"
         TextChanged="UpdateColorPickerDisplay"/>

I copied and pasted this for green and blue so everything is the same except for the name of the textbox. Then, to get the integer values, I have this:

private void UpdateColorPickerDisplay(object sender, TextChangedEventArgs e)
    {

        int R;
        int G;
        int B;

        if (int.TryParse(ColorPickerDisplayRed.Text, out R)) ;
        if (int.TryParse(ColorPickerDisplayGreen.Text, out G)) ;
        if (int.TryParse(ColorPickerDisplayBlue.Text, out B)) ;

        var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
        ColorPickerDisplay.Background = brush;
    }

But when I run it, I get an error that says "ColorPickerDisplayGreen was null.". Then I tried just setting the text for each box as a test and got the same error. I tried it for all 3 textboxes and it only worked for red. Is it because I'm calling the same method from all 3 text boxes?

CodePudding user response:

Add ? before accessing Text property & it will fix the issue

            int R;
            int G;
            int B;

            if (int.TryParse(ColorPickerDisplayRed?.Text, out R)) ;
            if (int.TryParse(ColorPickerDisplayGreen1?.Text, out G)) ;
            if (int.TryParse(ColorPickerDisplayBlue?.Text, out B)) ;

            var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
            ColorPickerDisplayRed.Background = brush;
  • Related