我试图用C#编写程序,以从另一个类动态创建PictureBox。
在这里完成了什么:
在类Form1中创建另一个类的对象,并在该类中创建我想要的对象(许多PictureBox'es)的调用过程
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Lines_online
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//trying to draw NxM table
//where N is horizontal cell count M is vertical cell count
Table tbl = new Table();
tbl.Tablenm(9, 9);
}
}
}
类表代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace Lines_online
{
public class Table : Form1
{
List<PictureBox> cell = new List<PictureBox>();
public void Tablenm(int n, int m)
{
for (int i = 0; i < n*m; i++)
{
PictureBox pict = new PictureBox();
cell.Add(pict);
cell[i].Size = new Size(20, 20);
cell[i].Location = new Point(30 + (i % n) * 19, 30 + (i / m) * 19);
cell[i].Image = Properties.Resources.lang20x20;
Controls.Add(cell[i]);
}
}
}
}
然后执行代码,它什么也不做,也不给出任何错误(我认为它会在某处创建对象,但不是在Form1窗口中定义)。如果将类Table中的过程移至Form1类,则可以正常工作,但我想从其他类进行控制以减少Form1中的代码大小。我试图在类表中创建Form1对象:
Form1 frm1 = new Form1();
它没有帮助。我在做错什么,或者对这个问题使用不好的方法?
注意:在您的代码中,您将从Form1继承表。这确实意味着Table代表了一种新的形式,而不是对当前现有形式的引用,因此它什么也不做。
在原始表单的Controls属性中,您只是添加了另一种表单,这绝对不是您需要的行为。
我以您的代码为起点并对其进行了一些修改。我确实认为这应该起作用。
创建您的类Table,但不要继承Form1。使您的课程看起来像以下内容:
public class Table
{
public List<PictureBox> Render(int n, int m)
{
List<PictureBox> returnList = new List<PictureBox>();
for (int i = 0; i < n*m; i++)
{
PictureBox pict = new PictureBox();
pict.Size = new Size(20, 20);
pict.Location = new Point(30 + (i % n) * 19, 30 + (i / m) * 19);
pict.Image = Properties.Resources.lang20x20;
returnList.Add(pict);
}
return returnList;
}
}
然后,以您的主要形式,可以调用您的方法:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var table = new Table();
IEnumerable<Control> controls = table.Render(10, 10);
foreach (var control in controls)
{ this.Controls.Add(control); }
}
}
我认为应该可以,但尚未测试。另请注意,此代码未优化。您应该将参数传递给函数,以使其更通用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句