更改标签文本错误C#

时间:2011-12-18 18:50:41

标签: c# visual-studio-2010 windows-forms-designer

我的程序停止使用此警告

  

WindowsFormsApplication10.exe中出现未处理的“System.NullReferenceException”类型异常

     

附加信息:对象引用未设置为的实例   对象

以下是停止的代码:

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

这只是一个带有Label的StatusStrip。我正在尝试更改该Label的文本。通常它适用于没有StatusStrip的Label。我的错是什么?

Visual Studio 2010 C#

5 个答案:

答案 0 :(得分:0)

我猜keepValues[lastTaken]为空。

所以keepValues[lastTaken].ToString();会给你一个NullReferenceException。

我建议使用调试器逐步执行程序,并检查哪个对象为空

答案 1 :(得分:0)

NullReferenceException表示该实例为null。通过访问null-instance,您将获得NullReferenceException。确保控件不为null。只需在悬停在它上面的线上设置一个断点,你就会看到错误。

答案 2 :(得分:0)

  1. keepValues集合不包含等于lastTaken
  2. 的键
  3. keepValues[lastTaken]存在,但其值为null

答案 3 :(得分:0)

我最好的猜测是keepValuesnulllastTaken索引/键(您的代码没有说明它是列表还是字典)在集合中不存在。通常的原因是表单设计器可能无法在初始化时传递外部数据。表单具有DesignMode属性,如果表单在设计器中运行,则可以使用该属性,如果需要,可以使用该属性提供一些模拟数据。

答案 4 :(得分:0)

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

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

这将创建例外

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

因此请记住用于从数组中访问值的数组和索引的长度。

相关问题