2015-03-31 66 views
0

我想寫一些代碼,顯示面板(網格[])的網格到更大的面板(gridHolder)。這裏是我到目前爲止的代碼:C#:製作面板的二維陣列

public void setupPanels(int x, int y) 
    { 

     grid = new Panel[y, x]; 
     this.Controls.Add(gridHolder); 
     gridHolder.Show(); 
     gridHolder.Location = new Point(0 , 0); 
     gridHolder.Size = new Size(x * PANEL_SIZE, y * PANEL_SIZE); 

     for (int i = 0; i < grid.GetLength(0); i++) 
     { 

      for (int j = 0; j < grid.GetLength(1); j++) 
      { 

       gridHolder.Controls.Add(grid[i, j]); 
       grid[i, j].Location = new Point(i * PANEL_SIZE, j * PANEL_SIZE); 
       gridHolder.Size = new Size(PANEL_SIZE, PANEL_SIZE); 

      } 

     } 



    } 

當我嘗試運行該程序,我得到一個調試錯誤說「的NullReferenceException是未處理」。我如何修復我的代碼?

+0

這將是有益的知道在哪一行,你得到「的NullReferenceException」。 – 2015-03-31 15:07:34

回答

0

很遠的猜測..但試試這個: 在你Page_Load方法改變內部代碼,以便它調用setupPanels方法會不會把它的每個條目,但只有在非回發來電,應該是這個樣子的行:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
     setupPanels(...) 
} 

這是一個完整的例子:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <asp:panel ID="gridHolder" runat="server"/> 
    </form> 
</body> 
</html> 



public partial class WebForm1 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
      SetupPanels(gridHolder, 40, 40, 6, 6); 
    } 

    private void SetupPanels(Panel panelsHolder, int widthPerPanel, int heightPerPanel, int panelsCountX, int panelsCountY) 
    { 
     panelsHolder.Style.Add("position","absolute"); 
     panelsHolder.Width = widthPerPanel*panelsCountX; 
     panelsHolder.Height = heightPerPanel*panelsCountY; 
     for (int y = 0; y < panelsCountY; y++) 
     { 
      for (int x = 0; x < panelsCountX; x++) 
      { 
       var gridPanel = new Panel 
       { 
        Width = widthPerPanel, 
        Height = heightPerPanel, 
        BackColor = Color.SandyBrown, 
        BorderColor = Color.Black, 
        BorderWidth = 5, 
       }; 
       gridPanel.Style.Add("position", "absolute"); 
       gridPanel.Style.Add("top", (x*widthPerPanel) + "px"); 
       gridPanel.Style.Add("left", (y*heightPerPanel) + "px"); 
       panelsHolder.Controls.Add(gridPanel); 
      } 
     } 
    } 

} 
+0

這似乎不是它。我環顧四周,它可能與面板類本身有關。編輯:顯然它不能做,因爲面板是一個類,而不是一個結構。 – Kimbabwe 2015-03-31 01:15:15

+0

沒有這樣的事情不能做 - 除了在圓角房間的角落撒尿。 – 2015-03-31 14:44:59