问题
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