How do I determine the cell being clicked on in a TableLayoutPanel?

Ayman Sharaf picture Ayman Sharaf · Mar 16, 2013 · Viewed 12.2k times · Source

I have a TableLayoutPanel and I want to add a control to the cell that I click on.

The problem is that I can't determine the cell that I click on at run time.

How do I determine the cell being clicked on?

Answer

Mohammad Dehghan picture Mohammad Dehghan · Mar 16, 2013

You can use GetColumnWidths and GetRowHeights methods to calculate the cell row and column index:

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);
}

Usage:

private void tableLayoutPanel1_Click(object sender, EventArgs e)
{
    var cellPos = GetRowColIndex(
        tableLayoutPanel1,
        tableLayoutPanel1.PointToClient(Cursor.Position));
}

But notice that the click event only is raised if the cell does not already contain a control.