动态创建按钮的小问题
1 有个类叫formChessboard,上边有个panel.当panel的MouseDown事件发生时,在点击的位置创建一个按钮,
这个按钮是Chessman类的对象.
panel的MouseDown事件处理函数:
- C# code
private void pnl_MouseDown(object sender, MouseEventArgs e){ chsman[nMousePositionOnChessboardX,nMousePositionOnChessboardY]=new Chessman();}//nMousePostionOnChessboardX代表按钮在panel上的位置,它乘以50就是按钮的Location.X,Location.Y同理
然后我把按钮的位置,大小等信息放到Chessman类的初始化函数里边,如下:
- C# code
private void InitializeComponent() { this.SuspendLayout(); // // Chessman // this.Name = "Chessman"; //this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Chessman_MouseClick); this.Paint += new System.Windows.Forms.PaintEventHandler(this.Chessman_Paint); this.ResumeLayout(false); this.Location = new Point(FormChessboard.nMousePositionOnChessboardX*nChessmanSizeWidth, FormChessboard.nMousePositionOnChessboardY*nChessmanSizeHeight); this.Size = new Size(nChessmanSizeWidth,nChessmanSizeHeight); Color clr = Color.FromArgb(255, 255, 255); this.BackColor = clr; this.BackgroundImage = global::ball2.Properties.Resources.Rad; // 我想把按钮的背景图片设置成Rad(已经存在的资源位图) // 报错如下:Error1' ball2.Properties.Resources' does not contain a definition for 'Rad' pnl.Controls.Add(this); //现在轮到把按钮添加到formChessboard.pnl上,可是提示我pnl不存在 //写成formChessboard.pnl.Controls.Add(this),提示我不是静态的 //把那个pnl定义改成static时,formChessboard类初始化pnl又有错误: //Static member 'ball2.FormChessboard.pnl' cannot be accessed with an instance reference; qualify it with a type name instead }
到底应该怎么写?我就想加在pnl上! 那个资源位图作为背景图片应该怎么写?
[解决办法]
不大清楚具体的写法,不过可以这样试一下:
在design模式下按你自己的要求做一个按钮,然后从xx.Designer.cs里找到相关的自动生成的代码,加到pnl_MouseDown里面去。
[解决办法]
Chessman类重载个构造函数,把pnl带到Chessman类中去
private Panel pnl = null;
public Chessman(Panel pnl)
{
this.pnl = pnl;
}
[解决办法]
根据你的代码可以判断InitializeComponent是Chessman类中的代码,你这样做首先就要判断pnl是否为null,
在指定了pnl属性后,才可以向pnl.controls做add操作
[解决办法]
看不懂你代码的意思。
[解决办法]
还没用过.学习!
[解决办法]
给MouseDown事件的委托添加方法
方法里面创建按钮啊