Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix row height of every row in TableLayoutPanel

I'm working on Windows c#.

Firstly, the things those can not be change as my need are following:

  1. The Size of TableLayoutPanel is fixed.
  2. The Total # of columns are fixed.

Now, I want to set a fix height for all rows but as increasing the rows, if I set the RowStyle property to Percent with 100.0F then it works fine for 3 to 4 items, but after 4-5 items, the control on one row overwrites controls on another row.

I have searched for this so more but i'm not able to get the proper answer. I have also tried the AutoSize, Percent, Absolute properties of RowStyle, even though it is not working.

So what to do and how? How can I achieve this?

Ultimately, I want to do same like as DataGridView of Windows C#.

Thanks in advance....

I'm working on WinForms...the sample code is here..

int cnt = tableLayout.RowCount = myDataTable.Rows.Count;

tableLayout.Size = new System.Drawing.Size(555, 200);

for (int i = 1; i <= cnt; i++)
{

    Label lblSrNo = new Label();
    lblSrNo.Text = i.ToString(); 

    TextBox txt = new TextBox();
    txt.Text = ""; 
    txt.Size = new System.Drawing.Size(69, 20);

    tableLayout.Controls.Add(lblSrNo, 0, i - 1);
    tableLayout.Controls.Add(txt, 1, i - 1);
}

tableLayout.RowStyles.Clear();

foreach (RowStyle rs in tableLayout.RowStyles)                
    tableLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));

The label and textboxes are working fine for 4-5 #of rows but whenever the #of row(in this case, variable cnt in for loop) increases, the rows are overwriting each other that is one control overwrite to another...I had drag-drop the TableLayoutPanel control and created just one row and 2 columns manually.

So please tell me how to do it.

like image 482
iVad Avatar asked Feb 21 '13 14:02

iVad


1 Answers

I'm still new to tableLayoutPanels myself, but I noticed that at the bottom of your code, you're Clearing all the rowstyles from the collection, then you're trying to iterate through them in your foreach loop.

You did this:

tableLayout.RowStyles.Clear();   //now you have zero rowstyles

foreach (RowStyle rs in tableLayout.RowStyles)   //this will never execute
    tableLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));

Try this instead.

TableLayoutRowStyleCollection styles =
    tableLayout.RowStyles;
foreach (RowStyle style in styles){
    // Set the row height to 20 pixels.
    style.SizeType = SizeType.Absolute;
    style.Height = 20;
}

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Edit: I just realized that adding N rows doesn't add N rowstyles that you can iterate through. I think what's happening is that you're adding N rows, but none of them have a rowstyles.

I suppose you can Clear() the rowstyles, then just add N rowstyles similar to how you're already doing.

like image 188
NL3294 Avatar answered Oct 19 '22 20:10

NL3294