Global array size determined by another form
I am trying to create a global 2-dimensional array who's size would depend on two values entered in another forms textboxes. However, I get an error saying that the values are not static.
public partial class Form2 : Form
{
Form1 frm = new Form1();
PictureBox[,] MyArray = new PictureBox[Convert.ToInt32(frm.textbox1.text), Convert.ToInt32(frm.textbox1.text)];
}
Since those textboxes are not sta开发者_如何学Gotic (the value in them can be changed), the error is given. I have tried multiple things to bypass this problem; I tried initializing a constant from those textboxes, but it gives the same error, I have also tried resizing the array, but Array.Resize does not work since it is multidimensional and Array.Copy does not work since I need the array to be global
To give you an idea of what I am trying to do, on the first form Form1, the user enters a width and length value. The user then presses confirm, and Form2 opens. The second form Form2 will have an array who's size is determined by the values the user entered. This array will serve to work with a grid also determined by the values entered by the user.
What is the way to bypass the non-static error and create an array with those values?
You cannot reference your instance (including instance fields) in field initializers, since the instance has not been constructed yet.
Move your code to the Form1
constructor.
When you instantiate 'frm' on Form2 you are not referencing the existing form by rather creating a new instance of type Form1.(Which you do not then ".show()")
Assuming you are launching form2 from form1 looking something like this:
protected void launchForm2()
{
Form2 form2 = new Form2();
form2.Show();
}
// you need to change that to look like this:
protected void launchForm2()
{
Form2 form2 = new Form2();
form2.Parent = this;
form2.Show();
}
Then in form2 you need to address the "Parent" like this:
//added to declare myArray global to the form.
PictureBox[,] MyArray;
// to make it 'global' to the application you will need to create some manner of "globalApplicationContext" and pass references of that around or use a 'baseForm' that holds a reference... there are (of course) other solutions as well to globalizing it..
protected void updateArray()
{
string textFromForm1 = ((Form1)this.Parent).textBox1.Text;
// remarked out after @Justin's comment...thx.
//PictureBox[,] MyArray = new PictureBox[Convert.ToInt32(textFromForm1), Convert.ToInt32(textFromForm1)];
MyArray = new PictureBox[Convert.ToInt32(textFromForm1), Convert.ToInt32(textFromForm1)];
}
This will keep your references in order...
Others have pointed to solutions, so this is just a followup. Communication between forms quickly gets very confusing. Anyways, you are placing way too much logic on the forms. Business logic should be separated from your GUI. Look into the Model-View-Controller pattern.
精彩评论