简体   繁体   English

C#中的条件运算符

[英]Conditional Operators in C#

I am trying to compare two values from a label and textbox. 我正在尝试比较标签和文本框中的两个值。 When the AvailQty is at 6 it is considered to be "Low" and if a user types in 4 or 10 it will display error because there's only 6 available. 当AvailQty为6时,它被视为“低”;如果用户键入4或10,则将显示错误,因为只有6个可用。

I have this: 我有这个:

if ((Int32.Parse(AvailQty.Text) <= 6) && (Int32.Parse(Qty.Text) > 6))
{
    lblAvailQty = "error";
}

This works but how can I make it so that if the user enters more than 6 or below 6 display error and do it in an efficient way because I feel like I am going to have a lot of if statements. 这行得通,但是我该如何做到这一点,以便如果用户输入的错误大于6或小于6,并以有效的方式进行操作,因为我感觉我将有很多if语句。

If you're doing this inside of some event handler you can just put single "return;" 如果要在某个事件处理程序中执行此操作,则只需将单个“ return;”放进去即可。 operator inside the same if () {} block as the last operator. 运算符位于与最后一个运算符相同的if(){}块中。

It will effectively interrupt execution of the event handler. 它将有效地中断事件处理程序的执行。

Example: 例:

if ((Int32.Parse(lblAvailQty.Text) <= 6) && (Int32.Parse(txtQty.Text) <= 6))
{
    lblAvailQty = "error";
    return;
}

So, when the available quantity is less than or equal to 6 it should error. 因此,当可用数量小于或等于6时,它应该会出错。 Also, if the requested quantity is greater than the available quantity, it should also error. 同样,如果请求的数量大于可用数量,则它也将出错。

I think this is what you're looking for: 我认为这是您要寻找的:

int avail = Int32.Parse(lblAvailQty.Text);
int req = Int32.Parse(txtQty.Text);

if (avail <= 6 || req > avail)
{
    //Display error
    //Do whatever else you need
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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