Search code examples
c#radio-buttonisnullorempty

Stop code if textbox is empty


I have a textbox tb_weight that is the input for a calculation and I've made a code with a messagebox that will pop up if the textbox is empty when pressing the calculate button:

if (string.IsNullOrEmpty(this.tb_weight.Text))
{
    MessageBox.Show("Textbox is empty");
}

I have radio buttons corresponding to a number that will be multiplied with the value written in the textbox. Below is the code for one of the buttons:

if (rb_wcf1.IsChecked == true)
{                
    int a = Int32.Parse(tb_weight.Text);
    b = (a * 1.03) / 1000;
    lbl_wll.Content = Math.Round(b, 2);
}

So if none of the radio buttons is selected and there is no text in the textbox, my messagebox will pop up. If I leave the textbox empty and check the radio button rb_wcf1 and the press the calculate button, the program will fail after closing the messagebox. I'm pretty new to programming and I'm not sure how to design this code better. If the textbox is empty and radio buttons has been checked, I don't want to the code in the radio buttons to initiate. Can anyone please give me some tips or guidance?


Solution

  • You already have a condition to check if the text box is empty:

    if (string.IsNullOrEmpty(this.tb_weight.Text))
    

    Just use that:

    if (!string.IsNullOrEmpty(this.tb_weight.Text))
    {
        if (rb_wcf1.IsChecked == true)
        {
            // perform your calculations
        }
    }
    

    Or invert the conditional to exit the method as a kind of guard clause:

    if (!string.IsNullOrEmpty(this.tb_weight.Text))
    {
        // show message
        return;
    }
    
    if (rb_wcf1.IsChecked == true)
    {
        // perform your calculations
    }
    // etc.
    

    There are many different ways to structure your logic, and what would be best is a combination of personal preference and how your code is currently structured (which we can't see from these snippets). But in general what you're looking to do is simply check if the text box is empty, which you already do.


    Side note: Int32.Parse() can throw an exception if the input can't be parsed to an integer. You might try this instead:

    int a;
    if (!Int32.TryParse(tb_weight.Text, out a))
    {
        // show an error
        return;
    }
    // continue with your logic
    

    That way if the input can't be parsed into an integer, a friendly error message will be shown instead of an exception.