none
C# System.NullReferenceException ?!?!

    Question

  •   Here is some example code that shows my problem:
    1 using System;  
    2 using System.Windows.Forms;  
    3  
    4 namespace sampel  
    5 {  
    6  
    7     internal sealed class Program  
    8     {  
    9         [STAThread]  
    10         private static void Main(string[] args)  
    11         {  
    12             Application.Run(new MainForm());  
    13         }  
    14           
    15     }  
    16       
    17     public partial class MainForm : Form  
    18     {  
    19         public MainForm()  
    20         {  
    21             InitializeComponent();  
    22         }  
    23  
    24         private void InitializeComponent()  
    25         {  
    26             this.ClientSize = new System.Drawing.Size(292, 271);  
    27             this.Name = "MainForm";  
    28             this.Text = "sampel";  
    29               
    30             String[] fils = System.IO.Directory.GetFileSystemEntries("c:\\");  
    31             this.label1 = new System.Windows.Forms.Label[fils.Length] ;  
    32             for (int i =0 ;i <= fils.Length-1 ; ++i)  
    33             {  
    34                 this.label1[i] = new System.Windows.Forms.Label();  
    35                 this.Container.Add(this.label1[i]); // <------  !?!?!  
    36                   
    37                 //Exception System.NullReferenceException was thrown in debuggee:  
    38                 //Objektreferensen har inte angetts till en instans av ett objekt.  
    39                   
    40                 //InitializeComponent() - d:\Documents and Settings\Administratör.MAD-YURI-PC.000\Mina dokument\SharpDevelop Projects\sampel\Program.cs:39,5  
    41                 //.ctor() - d:\Documents and Settings\Administratör.MAD-YURI-PC.000\Mina dokument\SharpDevelop Projects\sampel\Program.cs:23,4  
    42                 //Main() - d:\Documents and Settings\Administratör.MAD-YURI-PC.000\Mina dokument\SharpDevelop Projects\sampel\Program.cs:14,4  
    43  
    44             }  
    45         }  
    46         private System.Windows.Forms.Label[] label1;  
    47     }  
    48       
    49 }  
    50  
    Thanks in advance.
    Thursday, October 30, 2008 1:37 PM

Answers

  • Container is null on a form that is not contained.  Add your label to this.Controls, not this.Container.
    David Morton - http://blog.davemorton.net/
    • Marked as answer by mad-YuRi Thursday, October 30, 2008 2:39 PM
    Thursday, October 30, 2008 2:35 PM

All replies