Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get height and width of TableLayoutPanel cell in Windows Forms

Using a TableLayoutPanel in Windows Forms. I am using RowStyles and ColumnStyles with SizeType as AutoSize and Percent respectively. I need to find out the absolute height and width of a cell in which a particular control is placed.

TableLayoutPanelCellPosition pos = tableLayoutPanel1.GetCellPosition(button1);
int height = (int)tableLayoutPanel1.RowStyles[pos.Row].Height;
int width = (int)tableLayoutPanel1.ColumnStyles[pos.Column].Width;

Above, I am getting height as 0. RowStyle is with SizeType as AutoSize. Similarly, I am getting as 33.33. ColumnStyle is set with SizeType as Percent and Size = 33.33.

I need to get absolute size in pixels for the cell.

like image 954
Brij Avatar asked Dec 05 '12 14:12

Brij


2 Answers

For some odd reason, Microsoft decided to hide those functions from intellisense.

This should work as written:

  TableLayoutPanelCellPosition pos = tableLayoutPanel1.GetCellPosition(button1);
  int width = tableLayoutPanel1.GetColumnWidths()[pos.Column];
  int height = tableLayoutPanel1.GetRowHeights()[pos.Row];
like image 52
LarsTech Avatar answered Oct 03 '22 22:10

LarsTech


Microsoft chose to hide the GetColumnsWidths() method from Intellisense (using the attribute EditorBrowsableState.Never) likely because they never really finished implementing the GetColumnsWidths() method. The GetColumnsWidths() method returns an array as long as there is no control in the TableLayoutPanel that has a ColumnSpan value greater than 1. Once that condition exists, you're out of luck and the TableLayoutPanel's GetColumnsWidths() method will return an empty array instead.

An alternative is to use the TableLayoutPanel's ColumnStyles and RowStyles collections--which returns the width/height of each column/row, respectively when the column/row SizeType is Absolute. When it's Percent, the return value is a percentage value; when it's AutoSize, the return value appears to be 0. You can map a percent value to a pixel measurement by taking the total width of the TableLayoutPanel and subtracting the total width of any absolute columns then applying a percent calculation to the remaining pixels if no AutoSize columns are used (same applies to rows).

like image 22
Jazimov Avatar answered Oct 03 '22 22:10

Jazimov