如何确定在TableLayoutPanel中单击的单元格?

Aym*_*raf 3 c# tablelayoutpanel winforms

我有一个TableLayoutPanel,我想在我点击的单元格中添加一个控件.

问题是我无法确定在运行时单击的单元格.

如何确定单击的单元格?

Moh*_*han 9

您可以使用GetColumnWidthsGetRowHeights方法来计算单元格行和列索引:

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事件.

  • 这看起来与 2006 年 2 月发布在 [pcreview.co.uk](http://www.pcreview.co.uk/threads/tablelayoutpanel-get-cell-clicked.2410704/) 上的答案相同。 (2认同)