我试图编写一些显示面板网格(grid [])的代码到更大的面板(gridHolder)上。到目前为止,这是我的代码:
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);
}
}
}
当我尝试运行该程序时,我收到一个调试错误,说&#34; NullReferenceException未处理&#34;。我该如何修复我的代码?
答案 0 :(得分: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);
}
}
}
}