我有一个TableLayoutPanel
并且我想向我单击的单元格添加一个控件。
问题是我无法确定在运行时单击的单元格。
如何确定被点击的单元格?
我有一个TableLayoutPanel
并且我想向我单击的单元格添加一个控件。
问题是我无法确定在运行时单击的单元格。
如何确定被点击的单元格?
您可以使用GetColumnWidths
和GetRowHeights
方法来计算单元格的行和列索引:
Point? GetRowColIndex(TableLayoutPanel tlp, Point point)
{
if (point.X > tlp.Width || point.Y > tlp.Height)
return null;
int w = tlp.Width;
int h = tlp.Height;
int[] widths = tlp.GetColumnWidths();
int i;
for (i = widths.Length - 1; i >= 0 && point.X < w; i--)
w -= widths[i];
int col = i + 1;
int[] heights = tlp.GetRowHeights();
for (i = heights.Length - 1; i >= 0 && point.Y < h; i--)
h -= heights[i];
int row = i + 1;
return new Point(col, row);
}
用法:
private void tableLayoutPanel1_Click(object sender, EventArgs e)
{
var cellPos = GetRowColIndex(
tableLayoutPanel1,
tableLayoutPanel1.PointToClient(Cursor.Position));
}
但请注意,仅当单元格尚未包含控件时才会引发 click 事件。
这对我有用:
public TableLayoutPanel tableLayoutPanel { get; set; }
private void Form_Load(object sender, EventArgs e)
{
foreach (Panel space in this.tableLayoutPanel.Controls)
{
space.MouseClick += new MouseEventHandler(clickOnSpace);
}
}
public void clickOnSpace(object sender, MouseEventArgs e)
{
MessageBox.Show("Cell chosen: (" +
tableLayoutPanel.GetRow((Panel)sender) + ", " +
tableLayoutPanel.GetColumn((Panel)sender) + ")");
}
请注意,我的 tableLayoutPanel 是全局声明的,因此我可以直接使用它而无需将其传递给每个函数。此外,tableLayoutPanel 和其中的每个面板都是在其他地方完全以编程方式创建的(我的表单 [设计] 完全空白)。
我的回答是基于上面@Mohammad Dehghan的回答,但有几个优点:
i=0
而不是i=length
),这意味着以正确的顺序处理不同宽度或高度的列这是代码的更新版本:
public Point? GetIndex(TableLayoutPanel tlp, Point point)
{
// Method adapted from: stackoverflow.com/a/15449969
if (point.X > tlp.Width || point.Y > tlp.Height)
return null;
int w = 0, h = 0;
int[] widths = tlp.GetColumnWidths(), heights = tlp.GetRowHeights();
int i;
for (i = 0; i < widths.Length && point.X > w; i++)
{
w += widths[i];
}
int col = i - 1;
for (i = 0; i < heights.Length && point.Y + tlp.VerticalScroll.Value > h; i++)
{
h += heights[i];
}
int row = i - 1;
return new Point(col, row);
}
尼克的答案是最好的解决方案,除了它可以为在单元格中包含不同类型控件的 TableLayoutPanels 通用。只需将显式“面板”类型更改为“控制”:
public TableLayoutPanel tableLayoutPanel { get; set; }
private void Form_Load(object sender, EventArgs e)
{
foreach (Control c in this.tableLayoutPanel.Controls)
{
c.MouseClick += new MouseEventHandler(ClickOnTableLayoutPanel);
}
}
public void ClickOnTableLayoutPanel(object sender, MouseEventArgs e)
{
MessageBox.Show("Cell chosen: (" +
tableLayoutPanel.GetRow((Control)sender) + ", " +
tableLayoutPanel.GetColumn((Control)sender) + ")");
}
这很好用,不需要进行坐标数学来查找单击了哪个单元格。