2017-05-26 88 views
0

我有一個以一種方法編程創建的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

「如何從另一種方法訪問數組?」一點都不,因爲你的陣列只能在這種方法中生存。您必須在您的課堂中創建一個擁有gridview實例的成員。 – HimBromBeere

回答

1

可以移動grid類範圍:

public partial class Form1 : Form 
{ 
    DataGridView[] grid = null; 

    public void Form1_Load(object sender, EventArgs e) 
    {  
     ... 
     grid = new DataGridView[grid_num]; 
     ... 
    } 
} 
+0

非常感謝:) –

0

它必須要麼是兩個函數的作用域的變量(它仍然可以是一個設置它的函數),或者您必須將其作爲第二個函數的參數傳遞(僅在函數1調用函數2時起作用)。 「

」我不能聲明它是類的成員,因爲我不知道數組有多大,因爲它取決於文件「 這句話對我來說沒有意義。該陣列將始終採用相同數量的存儲空間,無論您在何處引用它。你顯然需要這兩個函數。所以它必須對這兩種功能都有效。

究竟是什麼問題,你試圖通過不使其成爲類成員來避免?

相關問題