C#Textbox textresult不会显示

时间:2015-08-09 05:02:54

标签: c#

这是用于检查第一个数字是否大于第二个数字的代码,但它没有按预期工作。任何人都可以建议原因并纠正我吗?

if (txtFirst.Text == "") 
{ 
    txtFirst.Text = "0"; 

    if (txtSecond.Text == "") 
    { 
        txtSecond.Text = "0"; 
        int first = Convert.ToInt32(txtFirst.Text); 
        int second = Convert.ToInt32(txtSecond.Text); 

        if (first < second) 
        {
            txtResult.Text = "TRUE"; 
        } 
        else 
        { 
            txtResult.Text = "FALSE"; 
        } 
    } 
}    

1 个答案:

答案 0 :(得分:2)

仅当两个文本框都为空("")时,您的方案才有效。如果你喜欢以下内容会更好:

if (txtFirst.Text == "") {txtFirst.Text = "0";}
if (txtSecond.Text == ""){txtSecond.Text = "0";}
// it is a good to check for null in this scenario since
// Convert.ToInt32() is not capable of handling null
int first = Convert.ToInt32(txtFirst.Text); 
int second = Convert.ToInt32(txtSecond.Text);
if (first < second){txtResult.Text = "TRUE";}
else{txtResult.Text = "FALSE";}