1

I am just messing around and seeing if i can do some simple stuff in c#. I'm making a program which uses an array of textboxes. Right now i am using the following code:

private TextBox[,] textboxes;

private void moveup()
{            
    textboxes = new TextBox[,] { { box00, box01 }, { box10, box11 } };
    textboxes[currentrow, currentcolumn].BackColor = Color.Black;
}

I'm actually using the text box array in a few methods similar to 'moveup', is there anyway I can define the textboxes that are contained in it just once? Thanks in advance! :)

1
  • @DustinDavis Is there anyway that I can define the textboxes inside the textbox[,] once, without having to declare them inside the method as I do in the code snippet. Reason being I am using the same array in other methods, and do not want to have to edit them all when i change the amount of textboxes Commented Jan 23, 2014 at 0:29

1 Answer 1

2

I think you want something like this if I understand your question

Just move the definition outside of a method. You can also do this inside of an initialize method

 public partial class Form1 : Form
{
    private TextBox[,] textboxes;

    public Form1()
    {
        InitializeComponent();
        Initialize();
    }

    private void Initialize()
    {
        textboxes = new TextBox[,] { { box00, box01 }, { box10, box11 } };
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

Then call Initialize from your constructor.

Update: replaced previous code with actual WinForms code (Assuming yhou're using WinForms)

Sign up to request clarification or add additional context in comments.

5 Comments

box00,box01,box10,box11 each show the error "A field initializer cannot reference the non-static field, method, or property 'snake2.Form1.box00'" in the first line of code you offered
@LucasHolmes I just updated with code for a WinForms app. Let me know if you're not using WinForms
Yeah I am using WinForms. That code works perfectly, could you please explain what Form1() does and what Initialize() does? thank you!
Form1() is your class constructor. It has the same name as the class, but is a method and has no return type. This is what is called when a new instance of Form1 is created. Then we just create a neat container method called Initialize that performs any initialization tasks (such as defining your array). We call initialize from the constructor so that textboxes gets setup as soon as your Form does.
Note that I use Initialize as the name but you can call it Setup or whatever you like

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.