我有一个项目,需要在Windows窗体应用程序上动态创建一个网格,每个单元格上都有一个点击监听器.
网格需要12 X 12
我已经研究过这个并且无法找到将网格添加到Windows窗体应用程序的方法.我见过WPF的解决方案,但没有看到Windows Forms的解决方案.
如果你能指出我正确的方向,将不胜感激任何帮助
网格将需要与战舰游戏一起使用
在您想要网格的表单中尝试此代码:
编辑:我添加了一种方法,通过新的BattleShipRow类在网格中放置12行12列.您可以通过多种方式将数据添加到网格中,但这会将这些对象的列表绑定到网格.
您可能需要调整尺寸以使显示方式符合您的要求.
最后,我将在LoadGridData中定义的battleShipGrid列表作为公共成员.当点击发生时,您可以根据游戏需要修改此BattleShipRow对象列表中的数据.
private System.Windows.Forms.DataGridView myNewGrid; // Declare a grid for this form
private List<BattleShipRow> battleShipGrid; // Declare this here so that you can use it later to manipulate the cell contents
private void Form1_Load(object sender, EventArgs e)
{
myNewGrid = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(myNewGrid)).BeginInit();
this.SuspendLayout();
myNewGrid.Parent = this; // You have to set the parent manually so that the grid is displayed on the form
myNewGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
myNewGrid.Location = new System.Drawing.Point(10, 10); // You will need to calculate this postion based on your other controls.
myNewGrid.Name = "myNewGrid";
myNewGrid.Size = new System.Drawing.Size(400, 400); // You said you need the grid to be 12x12. You can change the size here.
myNewGrid.TabIndex = 0;
myNewGrid.ColumnHeadersVisible = false; // You could turn this back on if you wanted, but this hides the headers that would say, "Cell1, Cell2...."
myNewGrid.RowHeadersVisible = false;
myNewGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
myNewGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
myNewGrid.CellClick += MyNewGrid_CellClick; // Set up an event handler for CellClick. You handle this in the MyNewGrid_CellClick method, below
((System.ComponentModel.ISupportInitialize)(myNewGrid)).EndInit();
this.ResumeLayout(false);
myNewGrid.Visible = true;
LoadGridData();
}
public class BattleShipRow
{
public string Cell1 { get; set; }
public string Cell2 { get; set; }
public string Cell3 { get; set; }
public string Cell4 { get; set; }
public string Cell5 { get; set; }
public string Cell6 { get; set; }
public string Cell7 { get; set; }
public string Cell8 { get; set; }
public string Cell9 { get; set; }
public string Cell10 { get; set; }
public string Cell11 { get; set; }
public string Cell12 { get; set; }
}
private void LoadGridData()
{
battleShipGrid = new List<BattleShipRow>();
for (var i = 0; i < 12; i++)
{
battleShipGrid.Add(new BattleShipRow());
}
myNewGrid.DataSource = battleShipGrid;
}
private void MyNewGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)