设置标签内容会导致问题 [英] Setting label content causes issues

查看:84
本文介绍了设置标签内容会导致问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将标签的内容设置为:如果我的文本框中的值大于6000,则应显示"Under-Run Bumper",如果不是,则显示 string.Empty"",但是当我尝试运行代码时,出现以下错误:

I'm trying to set a label's content to: if the value in my textbox is larger than 6000 it should display "Under-Run Bumper" and if not it should be string.Empty or "", but when I try to run my code, I get the following error:

对象引用未设置为对象的实例.

Object reference not set to an instance of an object.

有人可以告诉我为什么会这样吗?

Can someone please tell me why this is happening?

private void txtExternalLength_TextChanged(object sender, TextChangedEventArgs e)
{
    if (txtExternalLength.Text != string.Empty)
    {
        if (Convert.ToInt32(txtExternalLength.Text) >= 6000)
            lblUnderRunBumper.Content = "Under-Run Bumper";
        else lblUnderRunBumper.Content = ""; //Error here
    }
}

推荐答案

如果要获取文本框中的字符数,则应使用.Length. 这将返回一个带有字符数的整数.

If you want to get the numbers of chars in your textbox you should use .Length. This will return an Integer with the number of Chars.

private void txtExternalLength_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (txtExternalLength.Text != string.Empty)
        {
            if (txtExternalLength.Length >= 6000)
            {
                lblUnderRunBumper.Content = "Under-Run Bumper";
            }
            else 
            {
                lblUnderRunBumper.Content = ""; //Error here
            }
        }
    }

但是,如果您要使用在文本框中编写的Integer,则可以尝试以下操作:

But if you want to work with an Integer which is written in your Textbox u can try this:

    private void txtExternalLength_TextChanged(object sender, TextChangedEventArgs e)
            {
                if (txtExternalLength.Text != string.Empty)
                {
                    int count = 0;

                    bool result = Int32.TryParse(txtExternalLength.Text, out count);
                    // Int32.TryParse(input, out output) will try to Convert the text (string) of your Textbox to an Int32. If it is successfull the result will be true, else it will be false.
                    if (result && count >= 6000)
                    {
                        lblUnderRunBumper.Content = "Under-Run Bumper";
                    }
                    else 
                    {
                        lblUnderRunBumper.Content = ""; //Error here
                    }
                }
            }

这篇关于设置标签内容会导致问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆