Link to home
Start Free TrialLog in
Avatar of Raja Top
Raja TopFlag for Indonesia

asked on

ordering controls position in a panel C#

So I have a panel, I want to fill the panel with controls that based on the number of the column in my table. So, I code something like this

int i=0;
foreach (DataColumn col in ds.Tables["myTable"].Columns)
{                  
      CheckBox newCheckBox = new CheckBox();
      TextBox newTextBox = new TextBox();
      Panels1.Controls.Add(newCheckBox);
      Panels1.Controls.Add(newTextBox);
      newCheckBox.ID = "cb" + i;
      newCheckBox.Text = col.ToString();
      i++;
}

the result will create checkbox & textbox control in panel1, but it disordered (in terms of newline) because the length of each column is different like,

[]column1[//textbox1][]col2
[//textbox2][]column numb 3
[//textbox3]

how can I achieve something like this

[]column1            [//textbox1]
[]col2            [//textbox2]
[]column numb 3 [//textbox3]

can I inserting something like tabbing and newline in the line, what to do to expect that view?
or maybe we can create new panel + cb + tb on each iteration, but wont it take a bit long?
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Use TableLayoutPanel instead of panel as your container, then you can put your controls as child controls.
See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx
http://en.csharp-online.net/TableLayoutPanel
Avatar of Raja Top

ASKER

great, thanks for the solution.

Anyway, to change to row & col count in a loop, it is effective if I do

i=1
tableLayout.ColumnCount=2;
foreach (DataColumn col in ds.Tables["myTable"].Columns)
{                  
      CheckBox newCheckBox = new CheckBox();
      TextBox newTextBox = new TextBox();

      tableLayout.RowCount = i;

      Panels1.Controls.Add(newCheckBox, i-1, 0);
      Panels1.Controls.Add(newTextBox, i-1, 1);

      newCheckBox.ID = "cb" + i;
      newTextBox.ID = "tb" + i;
      newCheckBox.Text = col.ToString();
      i++;
}


or should I count for the column first, set the table layout row/column , and then iterate(adding controls)?
Your code looks OK. Profile it after you finish to see how long does it take.
If you know the size in advance, it is more efficient to create all row and columns before the iteration.
I forgot to say that Im use it on Aspx page. Since table layout panel is windows controls and not web controls, I have a problem to add my web control (checknox & textbox) to table layout panel. it said cannot convert web control to windows control. Can i still use table layout panel?
ASKER CERTIFIED SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks, though i decided not to use table layout panel ;]