我有一个 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));
}
但请注意,仅当单元格尚未包含控件时才会引发点击事件。
关于c# - 如何确定在 TableLayoutPanel 中单击的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15449504/