我在一个方法中以编程方式创建了一个dataGridViews数组。如何从其他方法访问数组? (在这种情况下按钮单击)。我无法宣布它是班级成员,因为我不知道数组有多大,因为它取决于文件
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(@"..\..\Diets.txt");
int diet_num = 0;
int grid_num = 0;
foreach (string x in lines) diet_num++;
grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;
Font dataGridFont = new Font("Microsoft Sans Serif",12, FontStyle.Bold);
Color c = Color.FromArgb(255,255,128);
DataGridView[] grid = new DataGridView[grid_num];
for (int i = 0; i < grid_num; i++)
{
grid[i] = new DataGridView();
grid[i].Tag = i;
grid[i].Parent = this;
grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
grid[i].Visible = true;
grid[i].RowHeadersVisible = false;
grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
grid[i].UserAddedRow += Form1_UserAddedRow;
grid[i].RowTemplate.Height = Constant.DATAGRID_ROW_HEIGHT;
grid[i].ColumnHeadersHeight = Constant.DATAGRID_ROW_HEIGHT;
grid[i].AllowUserToResizeColumns = false;
grid[i].AllowUserToResizeRows = false;
grid[i].MultiSelect = false;
grid[i].ColumnHeadersHeightChanged += Form1_ColumnHeadersHeightChanged;
grid[i].MouseLeave += Form1_MouseLeave;
grid[i].Font = dataGridFont;
grid[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
grid[i].ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
grid[i].ColumnHeadersDefaultCellStyle.BackColor = c;
grid[i].EnableHeadersVisualStyles = false;
}
this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;
int count = 0;
foreach (string x in lines)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.Width = Constant.DATAGRID_COLUMN_SIZE;
col.HeaderText = x;
int colIndex = grid[count/12].Columns.Add(col);
count++;
}
}
private void button1_Click(object sender, EventArgs e)
{
grid[0].Visible = false; //can't do that
}
}
答案 0 :(得分:1)
您可以将grid
移至课程范围:
public partial class Form1 : Form
{
DataGridView[] grid = null;
public void Form1_Load(object sender, EventArgs e)
{
...
grid = new DataGridView[grid_num];
...
}
}
答案 1 :(得分:0)
它必须是两个函数的范围变量(它仍然可以是设置它的一个函数),或者你必须将它作为第二个函数的参数(仅当函数1调用函数2时才有效)。
&#34;我无法宣布它是班级成员,因为我不知道阵列有多大,因为它取决于文件&#34; 这句话对我来说毫无意义。该阵列将始终采用相同数量的存储,无需引用它。你显然在两个功能中都需要它。所以它必须适用于这两种功能。
你试图通过不让它成为班级成员来避免什么问题?