Setting label content causes issues

…衆ロ難τιáo~ 提交于 2019-12-24 15:42:32

问题


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
    }
}

回答1:


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
            }
        }
    }

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
                    }
                }
            }


来源:https://stackoverflow.com/questions/36337084/setting-label-content-causes-issues

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!