In C# how does one access the elements of an array of control labels created at runtime?












1















Over the years I've done a significant amount of programming in various forms of BASIC, including Visual Basic. When it comes to C# I'm quite confused. Below is the form load code for a mastermind program I am creating in C#. Everything works, until I try to create my marking routine.



 public void Form1_Load(object sender, EventArgs e)
{
//int columns = 14;
Label[,] board = new Label[5,14];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 14; j++)
{
board[i,j] = new Label();
board[i,j].AutoSize = false;
board[i,j].Size = Dummy.Size;
board[i,j].BorderStyle = BorderStyle.Fixed3D;
board[i,j].BackColor = Color.Beige;
board[i,j].Location = new Point(i * Dummy.Width+2, j * Dummy.Height+2);
board[i,j].Name = "board" + i.ToString() + "," + j.ToString();
board[i,j].Width = Dummy.Width - 4;
board[i,j].Height = Dummy.Height - 4;
board[i,j].TabIndex = 0;
//board[i][j].Text = i.ToString() +" "+ j.ToString();
panel2.Controls.Add(board[i,j]);
board[i,j].Click += new EventHandler(Label1_Click);
}
P2.Click += new EventHandler(P1_Click);
P3.Click += new EventHandler(P1_Click);
P4.Click += new EventHandler(P1_Click);
P5.Click += new EventHandler(P1_Click);
P6.Click += new EventHandler(P1_Click);
P7.Click += new EventHandler(P1_Click);
P8.Click += new EventHandler(P1_Click);
}
int marker = 14;
int each = 5;
Label[,] mark = new Label[each,marker];
// Instantiating all the buttons in the array
for (int i = 0; i < each; i++)
{
for (int j = 0; j < marker; j++)
{
mark[i, j] = new Label();
mark[i, j].AutoSize=false;
mark[i, j].Size = Minnie.Size;
mark[i, j].BorderStyle = Minnie.BorderStyle;
mark[i, j].BackColor = Color.Blue;
mark[i, j].Left = i * (Minnie.Width+2)+3;
mark[i, j].Top = j * Dummy.Height+10;
panel3.Controls.Add(mark[i, j]);
}
}
}


This creates the playing 'holes' for guesses, and smaller marking 'holes' in panels 2 and 3, respectively. The playing part works fine as I have a selection panel that allows the user to choose colors and then 'place' the colors by clicking the board holes array. The various colours are matched by numbers which I append to the .Tag of board elements when they are clicked. The diffculty comes when I try to read the .Tags to assess the guesses for marking. Here is the code that is not working:



    public void button1_Click(object sender, EventArgs e)
{
int r;
for (r=0;r<5;r++) {
textBox1.Text = textBox1.Text + board[0,r].Tag;
//board[0, r].BackColor = Color.Azure;
}
}


The board[0, r].BackColor = Color.Azure; was an attempt to isolate where the error derives. It generated the same error, so it seems that the button routine knows that 'board' exists but doesn't acknowledge or is unable to access the subscripted elements. The error generated is:



▶ $exception {"Object reference not set to an instance of an object."} System.NullReferenceException



What do I need to do in order to overcome this difficulty?



Thanks in advance,



Cam










share|improve this question























  • board is a local variable in Form1_Load() method. Not accessible from button1_Click().

    – wannadream
    Nov 17 '18 at 2:47











  • Just like VB.NET, where you declare a variable determines its scope

    – None of the Above
    Nov 17 '18 at 2:50











  • Thanks, wanndream, but how do I make the variable public so it will be available?

    – W. C. Bastedo
    Nov 17 '18 at 2:53











  • Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

    – W. C. Bastedo
    Nov 17 '18 at 2:54






  • 1





    Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

    – Gabriel Luci
    Nov 17 '18 at 3:00
















1















Over the years I've done a significant amount of programming in various forms of BASIC, including Visual Basic. When it comes to C# I'm quite confused. Below is the form load code for a mastermind program I am creating in C#. Everything works, until I try to create my marking routine.



 public void Form1_Load(object sender, EventArgs e)
{
//int columns = 14;
Label[,] board = new Label[5,14];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 14; j++)
{
board[i,j] = new Label();
board[i,j].AutoSize = false;
board[i,j].Size = Dummy.Size;
board[i,j].BorderStyle = BorderStyle.Fixed3D;
board[i,j].BackColor = Color.Beige;
board[i,j].Location = new Point(i * Dummy.Width+2, j * Dummy.Height+2);
board[i,j].Name = "board" + i.ToString() + "," + j.ToString();
board[i,j].Width = Dummy.Width - 4;
board[i,j].Height = Dummy.Height - 4;
board[i,j].TabIndex = 0;
//board[i][j].Text = i.ToString() +" "+ j.ToString();
panel2.Controls.Add(board[i,j]);
board[i,j].Click += new EventHandler(Label1_Click);
}
P2.Click += new EventHandler(P1_Click);
P3.Click += new EventHandler(P1_Click);
P4.Click += new EventHandler(P1_Click);
P5.Click += new EventHandler(P1_Click);
P6.Click += new EventHandler(P1_Click);
P7.Click += new EventHandler(P1_Click);
P8.Click += new EventHandler(P1_Click);
}
int marker = 14;
int each = 5;
Label[,] mark = new Label[each,marker];
// Instantiating all the buttons in the array
for (int i = 0; i < each; i++)
{
for (int j = 0; j < marker; j++)
{
mark[i, j] = new Label();
mark[i, j].AutoSize=false;
mark[i, j].Size = Minnie.Size;
mark[i, j].BorderStyle = Minnie.BorderStyle;
mark[i, j].BackColor = Color.Blue;
mark[i, j].Left = i * (Minnie.Width+2)+3;
mark[i, j].Top = j * Dummy.Height+10;
panel3.Controls.Add(mark[i, j]);
}
}
}


This creates the playing 'holes' for guesses, and smaller marking 'holes' in panels 2 and 3, respectively. The playing part works fine as I have a selection panel that allows the user to choose colors and then 'place' the colors by clicking the board holes array. The various colours are matched by numbers which I append to the .Tag of board elements when they are clicked. The diffculty comes when I try to read the .Tags to assess the guesses for marking. Here is the code that is not working:



    public void button1_Click(object sender, EventArgs e)
{
int r;
for (r=0;r<5;r++) {
textBox1.Text = textBox1.Text + board[0,r].Tag;
//board[0, r].BackColor = Color.Azure;
}
}


The board[0, r].BackColor = Color.Azure; was an attempt to isolate where the error derives. It generated the same error, so it seems that the button routine knows that 'board' exists but doesn't acknowledge or is unable to access the subscripted elements. The error generated is:



▶ $exception {"Object reference not set to an instance of an object."} System.NullReferenceException



What do I need to do in order to overcome this difficulty?



Thanks in advance,



Cam










share|improve this question























  • board is a local variable in Form1_Load() method. Not accessible from button1_Click().

    – wannadream
    Nov 17 '18 at 2:47











  • Just like VB.NET, where you declare a variable determines its scope

    – None of the Above
    Nov 17 '18 at 2:50











  • Thanks, wanndream, but how do I make the variable public so it will be available?

    – W. C. Bastedo
    Nov 17 '18 at 2:53











  • Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

    – W. C. Bastedo
    Nov 17 '18 at 2:54






  • 1





    Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

    – Gabriel Luci
    Nov 17 '18 at 3:00














1












1








1








Over the years I've done a significant amount of programming in various forms of BASIC, including Visual Basic. When it comes to C# I'm quite confused. Below is the form load code for a mastermind program I am creating in C#. Everything works, until I try to create my marking routine.



 public void Form1_Load(object sender, EventArgs e)
{
//int columns = 14;
Label[,] board = new Label[5,14];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 14; j++)
{
board[i,j] = new Label();
board[i,j].AutoSize = false;
board[i,j].Size = Dummy.Size;
board[i,j].BorderStyle = BorderStyle.Fixed3D;
board[i,j].BackColor = Color.Beige;
board[i,j].Location = new Point(i * Dummy.Width+2, j * Dummy.Height+2);
board[i,j].Name = "board" + i.ToString() + "," + j.ToString();
board[i,j].Width = Dummy.Width - 4;
board[i,j].Height = Dummy.Height - 4;
board[i,j].TabIndex = 0;
//board[i][j].Text = i.ToString() +" "+ j.ToString();
panel2.Controls.Add(board[i,j]);
board[i,j].Click += new EventHandler(Label1_Click);
}
P2.Click += new EventHandler(P1_Click);
P3.Click += new EventHandler(P1_Click);
P4.Click += new EventHandler(P1_Click);
P5.Click += new EventHandler(P1_Click);
P6.Click += new EventHandler(P1_Click);
P7.Click += new EventHandler(P1_Click);
P8.Click += new EventHandler(P1_Click);
}
int marker = 14;
int each = 5;
Label[,] mark = new Label[each,marker];
// Instantiating all the buttons in the array
for (int i = 0; i < each; i++)
{
for (int j = 0; j < marker; j++)
{
mark[i, j] = new Label();
mark[i, j].AutoSize=false;
mark[i, j].Size = Minnie.Size;
mark[i, j].BorderStyle = Minnie.BorderStyle;
mark[i, j].BackColor = Color.Blue;
mark[i, j].Left = i * (Minnie.Width+2)+3;
mark[i, j].Top = j * Dummy.Height+10;
panel3.Controls.Add(mark[i, j]);
}
}
}


This creates the playing 'holes' for guesses, and smaller marking 'holes' in panels 2 and 3, respectively. The playing part works fine as I have a selection panel that allows the user to choose colors and then 'place' the colors by clicking the board holes array. The various colours are matched by numbers which I append to the .Tag of board elements when they are clicked. The diffculty comes when I try to read the .Tags to assess the guesses for marking. Here is the code that is not working:



    public void button1_Click(object sender, EventArgs e)
{
int r;
for (r=0;r<5;r++) {
textBox1.Text = textBox1.Text + board[0,r].Tag;
//board[0, r].BackColor = Color.Azure;
}
}


The board[0, r].BackColor = Color.Azure; was an attempt to isolate where the error derives. It generated the same error, so it seems that the button routine knows that 'board' exists but doesn't acknowledge or is unable to access the subscripted elements. The error generated is:



▶ $exception {"Object reference not set to an instance of an object."} System.NullReferenceException



What do I need to do in order to overcome this difficulty?



Thanks in advance,



Cam










share|improve this question














Over the years I've done a significant amount of programming in various forms of BASIC, including Visual Basic. When it comes to C# I'm quite confused. Below is the form load code for a mastermind program I am creating in C#. Everything works, until I try to create my marking routine.



 public void Form1_Load(object sender, EventArgs e)
{
//int columns = 14;
Label[,] board = new Label[5,14];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 14; j++)
{
board[i,j] = new Label();
board[i,j].AutoSize = false;
board[i,j].Size = Dummy.Size;
board[i,j].BorderStyle = BorderStyle.Fixed3D;
board[i,j].BackColor = Color.Beige;
board[i,j].Location = new Point(i * Dummy.Width+2, j * Dummy.Height+2);
board[i,j].Name = "board" + i.ToString() + "," + j.ToString();
board[i,j].Width = Dummy.Width - 4;
board[i,j].Height = Dummy.Height - 4;
board[i,j].TabIndex = 0;
//board[i][j].Text = i.ToString() +" "+ j.ToString();
panel2.Controls.Add(board[i,j]);
board[i,j].Click += new EventHandler(Label1_Click);
}
P2.Click += new EventHandler(P1_Click);
P3.Click += new EventHandler(P1_Click);
P4.Click += new EventHandler(P1_Click);
P5.Click += new EventHandler(P1_Click);
P6.Click += new EventHandler(P1_Click);
P7.Click += new EventHandler(P1_Click);
P8.Click += new EventHandler(P1_Click);
}
int marker = 14;
int each = 5;
Label[,] mark = new Label[each,marker];
// Instantiating all the buttons in the array
for (int i = 0; i < each; i++)
{
for (int j = 0; j < marker; j++)
{
mark[i, j] = new Label();
mark[i, j].AutoSize=false;
mark[i, j].Size = Minnie.Size;
mark[i, j].BorderStyle = Minnie.BorderStyle;
mark[i, j].BackColor = Color.Blue;
mark[i, j].Left = i * (Minnie.Width+2)+3;
mark[i, j].Top = j * Dummy.Height+10;
panel3.Controls.Add(mark[i, j]);
}
}
}


This creates the playing 'holes' for guesses, and smaller marking 'holes' in panels 2 and 3, respectively. The playing part works fine as I have a selection panel that allows the user to choose colors and then 'place' the colors by clicking the board holes array. The various colours are matched by numbers which I append to the .Tag of board elements when they are clicked. The diffculty comes when I try to read the .Tags to assess the guesses for marking. Here is the code that is not working:



    public void button1_Click(object sender, EventArgs e)
{
int r;
for (r=0;r<5;r++) {
textBox1.Text = textBox1.Text + board[0,r].Tag;
//board[0, r].BackColor = Color.Azure;
}
}


The board[0, r].BackColor = Color.Azure; was an attempt to isolate where the error derives. It generated the same error, so it seems that the button routine knows that 'board' exists but doesn't acknowledge or is unable to access the subscripted elements. The error generated is:



▶ $exception {"Object reference not set to an instance of an object."} System.NullReferenceException



What do I need to do in order to overcome this difficulty?



Thanks in advance,



Cam







c#






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 17 '18 at 2:41









W. C. BastedoW. C. Bastedo

43




43













  • board is a local variable in Form1_Load() method. Not accessible from button1_Click().

    – wannadream
    Nov 17 '18 at 2:47











  • Just like VB.NET, where you declare a variable determines its scope

    – None of the Above
    Nov 17 '18 at 2:50











  • Thanks, wanndream, but how do I make the variable public so it will be available?

    – W. C. Bastedo
    Nov 17 '18 at 2:53











  • Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

    – W. C. Bastedo
    Nov 17 '18 at 2:54






  • 1





    Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

    – Gabriel Luci
    Nov 17 '18 at 3:00



















  • board is a local variable in Form1_Load() method. Not accessible from button1_Click().

    – wannadream
    Nov 17 '18 at 2:47











  • Just like VB.NET, where you declare a variable determines its scope

    – None of the Above
    Nov 17 '18 at 2:50











  • Thanks, wanndream, but how do I make the variable public so it will be available?

    – W. C. Bastedo
    Nov 17 '18 at 2:53











  • Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

    – W. C. Bastedo
    Nov 17 '18 at 2:54






  • 1





    Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

    – Gabriel Luci
    Nov 17 '18 at 3:00

















board is a local variable in Form1_Load() method. Not accessible from button1_Click().

– wannadream
Nov 17 '18 at 2:47





board is a local variable in Form1_Load() method. Not accessible from button1_Click().

– wannadream
Nov 17 '18 at 2:47













Just like VB.NET, where you declare a variable determines its scope

– None of the Above
Nov 17 '18 at 2:50





Just like VB.NET, where you declare a variable determines its scope

– None of the Above
Nov 17 '18 at 2:50













Thanks, wanndream, but how do I make the variable public so it will be available?

– W. C. Bastedo
Nov 17 '18 at 2:53





Thanks, wanndream, but how do I make the variable public so it will be available?

– W. C. Bastedo
Nov 17 '18 at 2:53













Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

– W. C. Bastedo
Nov 17 '18 at 2:54





Where, Disaffected, do I declare the variable so it will be available within the scope of the button?

– W. C. Bastedo
Nov 17 '18 at 2:54




1




1





Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

– Gabriel Luci
Nov 17 '18 at 3:00





Are you sure you weren't declaring another board variable somewhere else? I find it surprising that the compiler didn't throw an error in button1_Click if the only board variable was declared in Form1_Load.

– Gabriel Luci
Nov 17 '18 at 3:00












1 Answer
1






active

oldest

votes


















1














Each variable has a scope: the section of code where that variable is valid. If you define it in a method, then the variable can only be used within that method.



So in this case, if you want to use that variable in multiple methods, you need to declare in a scope that encompasses those methods. In this case, that is your Form1 class - so just inside the declaration of the class, but outside any method.



But you also need to remove the declaration inside Form1_Load too, otherwise you'll end up with two variables with the same name and different scopes. They may have the same name, but they will refer to two different places in memory and not hold the same data. When you use board inside Form1_Load you will refer to the one declared inside that method, and it will be destroyed as soon as the method finishes.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347714%2fin-c-sharp-how-does-one-access-the-elements-of-an-array-of-control-labels-create%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Each variable has a scope: the section of code where that variable is valid. If you define it in a method, then the variable can only be used within that method.



    So in this case, if you want to use that variable in multiple methods, you need to declare in a scope that encompasses those methods. In this case, that is your Form1 class - so just inside the declaration of the class, but outside any method.



    But you also need to remove the declaration inside Form1_Load too, otherwise you'll end up with two variables with the same name and different scopes. They may have the same name, but they will refer to two different places in memory and not hold the same data. When you use board inside Form1_Load you will refer to the one declared inside that method, and it will be destroyed as soon as the method finishes.






    share|improve this answer




























      1














      Each variable has a scope: the section of code where that variable is valid. If you define it in a method, then the variable can only be used within that method.



      So in this case, if you want to use that variable in multiple methods, you need to declare in a scope that encompasses those methods. In this case, that is your Form1 class - so just inside the declaration of the class, but outside any method.



      But you also need to remove the declaration inside Form1_Load too, otherwise you'll end up with two variables with the same name and different scopes. They may have the same name, but they will refer to two different places in memory and not hold the same data. When you use board inside Form1_Load you will refer to the one declared inside that method, and it will be destroyed as soon as the method finishes.






      share|improve this answer


























        1












        1








        1







        Each variable has a scope: the section of code where that variable is valid. If you define it in a method, then the variable can only be used within that method.



        So in this case, if you want to use that variable in multiple methods, you need to declare in a scope that encompasses those methods. In this case, that is your Form1 class - so just inside the declaration of the class, but outside any method.



        But you also need to remove the declaration inside Form1_Load too, otherwise you'll end up with two variables with the same name and different scopes. They may have the same name, but they will refer to two different places in memory and not hold the same data. When you use board inside Form1_Load you will refer to the one declared inside that method, and it will be destroyed as soon as the method finishes.






        share|improve this answer













        Each variable has a scope: the section of code where that variable is valid. If you define it in a method, then the variable can only be used within that method.



        So in this case, if you want to use that variable in multiple methods, you need to declare in a scope that encompasses those methods. In this case, that is your Form1 class - so just inside the declaration of the class, but outside any method.



        But you also need to remove the declaration inside Form1_Load too, otherwise you'll end up with two variables with the same name and different scopes. They may have the same name, but they will refer to two different places in memory and not hold the same data. When you use board inside Form1_Load you will refer to the one declared inside that method, and it will be destroyed as soon as the method finishes.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 17 '18 at 3:22









        Gabriel LuciGabriel Luci

        10.8k11424




        10.8k11424






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347714%2fin-c-sharp-how-does-one-access-the-elements-of-an-array-of-control-labels-create%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings