我有一個以一種方法編程創建的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
}
}
「如何從另一種方法訪問數組?」一點都不,因爲你的陣列只能在這種方法中生存。您必須在您的課堂中創建一個擁有gridview實例的成員。 – HimBromBeere