Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

Getting the cell location based on the mouse click of tablelayoutpanel in c#

$
0
0

I have written the following code from one of your questions to get the location of the cell and after getting that location I want to add the user control which I have made.

        

private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
        {
            var pt = new Point(e.X, e.Y);


            var colWidths = this.tableLayoutPanel1.GetColumnWidths();
            var rowHeights = this.tableLayoutPanel1.GetRowHeights();

            int col = -1, row = -1;
            int offset = 0;
            for (int iCol = 0; iCol < this.tableLayoutPanel1.ColumnCount; ++iCol)
            {
                if (pt.X >= offset && pt.X <= (offset + colWidths[iCol]))
                {
                    col = iCol;
                    break;
                }

                offset += colWidths[iCol];
            }

            offset = 0;
            for (int iRow = 0; iRow < this.tableLayoutPanel1.RowCount; ++iRow)
            {
                if (pt.Y >= offset && pt.Y <= (offset + rowHeights[iRow]))
                {
                    row = iRow;
                    break;
                }

                offset += rowHeights[iRow];
            }

            MessageBox.Show(String.Format("row = {0}, col = {1}", row, col));
            tableLayoutPanel1.Controls.Add(new Rack(), col, row);

}


The major problem is that when the row size increases from 2 onwards it does not  gives the right location of the row where as columns are working fine.

Why is this issue coming?

and What is the offset in this code as I have copied it from one of your questions.


Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>