简体   繁体   中英

Changing Label Text error C#

My program stops working with this warning

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication10.exe

Additional information: Object reference not set to an instance of an object.

Here is the code where it stops:

string stripStatusL = "some text: " + keepValues[lastTaken].ToString();
                toolStripStatusLabel1.Text = stripStatusL;

It's just a StatusStrip with Label in. I'm trying to change the text of that Label. Usually it works for Label without StatusStrip. What is my mistake?

Visual Studio 2010 C#

I'd guess keepValues[lastTaken] is null.

so keepValues[lastTaken].ToString(); will give you a NullReferenceException.

I'd suggest stepping through the program with the debugger, and check which object is null

NullReferenceException means that the instance is null. By accessing a null-instance, you get the NullReferenceException. Make sure that the control is not null. Just set a breakpoint at the line on hover over it and you'll see whats wrong.

  1. the keepValues collection does not contain a key equal to lastTaken , or
  2. keepValues[lastTaken] exists but its value is null

My best guess would be that keepValues is null or that lastTaken index/key (your code doesn't say whether it's a list or dictionary) does not exist in the collection. The usual reason for that is that the forms designer might not be able to pass in external data on initialization. Forms have a DesignMode property which is true if the form is run in the designer which you can use to provide some mock data if required.

string[] keepValues=new string[5];
int lastTaken=6;

string temp=keepValues[lastTaken].ToString();

This will create the exception

 An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication10.exe Additional information: Object reference not set to an instance of an object. 

So keep in mind the length of array and index you are using to access value from array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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