Okay, i have an 8X8 grid, i want to use control arrays to create labels instead of creating each manually so that it is less repetitive code and easier to control when i try to switch the colors of each label on the gird.

namespace app1
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent(){
             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            for (int a = 0; a < 8; a++)
            {
                for (int b = 0; b < 8; b++)
                {
                   this.lbls[a,b] = new System.Windows.Forms.Label();
                   this.Controls.Add(this.lbls[a,b]);
                   lbls[a, b].Text = "hello";
                }
            }
        }
        #endregion
        private System.Windows.Forms.Label[,] lbls;
    }
}

I get a warning on "private System.Windows.Forms.Label[,] lbls;" saying "Field 'Chess.Form1.lbls' is never assigned to, and will always have its default value null"

and after i run it i get a "System.NullReferenceException was unhandled" error at "this.lbls[a,b] = new System.Windows.Forms.Label();" saying "Object reference not set to an instance of an object."

I don't understand why, any help would be appreciated.

Recommended Answers

All 3 Replies

You need to instantiate the array before you can use it.

Consider this example:

int[] myArray;
        myArray[0] = 10; // error: Use of unassigned local variable 'myArray'

It should be something like:

int[] myArray;
        myArray = new int[5]; // instantiate array
        myArray[0] = 10;

Seems you are putting your own code in your XXX.designer.cs file.
You should do that in the XXX.cs file.
The XXX.designer.cs file is maintained by Visual Studio, it may overwrite anything you put in there.

Ohh i see, i never have a line that says

Label[,] lbls = new Label[8,8];

and thanks for the info i moved my code to XXX.cs

thanks for everyone's help ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.