Aym*_*raf 3 c# tablelayoutpanel winforms
我有一个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);
}
Run Code Online (Sandbox Code Playgroud)
用法:
private void tableLayoutPanel1_Click(object sender, EventArgs e)
{
var cellPos = GetRowColIndex(
tableLayoutPanel1,
tableLayoutPanel1.PointToClient(Cursor.Position));
}
Run Code Online (Sandbox Code Playgroud)
但请注意,如果单元格尚未包含控件,则仅引发click事件.