How to get the position of the paticular cell that the user click on in tablelayout in c#

StackOverflow https://stackoverflow.com/questions/20682317

  •  19-09-2022
  •  | 
  •  

Question

How can I get the value of the cell index where the user has clicked in tablelayoutpanel. I want to get the value of column and row and then show it in messagebox.

How can i achieve this using c# ?

Was it helpful?

Solution

You can get the location like this:

private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
{
    int row = 0;
    int verticalOffset = 0;
    foreach (int h in tableLayoutPanel1.GetRowHeights())
    {
        int column = 0;
        int horizontalOffset = 0;
        foreach(int w in tableLayoutPanel1.GetColumnWidths())
        {
            Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);
            if(rectangle.Contains(e.Location))
            {
                Trace.WriteLine(String.Format("row {0}, column {1} was clicked", row, column));
                return;
            }
            horizontalOffset += w;
            column++;
        }
        verticalOffset += h;
        row++;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top