简体   繁体   中英

Validate user input with multiple criteria c#

I need to validate input based on whether or not it's a number and whether or not it exceeds inventory levels.

So far I can check for inventory level, but I only know how to use tryparse to check if its a number, and I don't want to output anything. Here's what I have so far. It gives an error because I didn't give it a variable.

if (ckbSingle.IsChecked.Value)
            {
                if (int.TryParse(txtSingQuan.Text, out Convert.ToInt32(txtSingQuan.Text)))
                if ((singleespresso.DunkinInventory - Convert.ToInt32(txtSingQuan.Text)) <= 0)
                {
                    MessageBox.Show("Espresso low in stock.");

                }
                else
                {
                    ProductList.Add("Single Espresso");
                }

            }

I want it to allow me to continue with the code if the input is appropriate and show a message box if it's not.

It gives an error because I didn't give it a variable

Then give it one:

if (ckbSingle.IsChecked.Value)
{
    if (int.TryParse(txtSingQuan.Text, out int qty) && qty >= singleespresso.DunkinInventory)
    {
        // Input is a valid number and is greater than or equals to stock
        ProductList.Add("Single Espresso");

        // qty variable is accessible in that scope if need be
    }
    else
    {
        // Input is either not a number or lower than stock
        MessageBox.Show("Espresso low in stock.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM