简体   繁体   中英

Creating C# winform simple dynamic controls

        private void CreateNewControl()
        {
            List<Control> list = new List<Control>();
            TableLayoutPanel layout = new TableLayoutPanel();
            layout.Dock = DockStyle.Fill;
            this.Controls.Add(layout);
            layout.ColumnCount = 3;
            layout.GrowStyle = TableLayoutPanelGrowStyle.AddRows;

            for (int i = 0; i < 9; i++)
            {

                if (wantedType == DevExpress.XtraEditors.CheckEdit)
                {

                    CheckBox chk = new CheckBox();
                    chk.Tag = i;

                    layout.Controls.Add(chk);
                    layout.AutoScroll = true;

                }


                if (wantedType ==  LabelControl)
                {
                    Label chk = new Label();

                    chk.Tag = i;

                    layout.Controls.Add(chk);
                    layout.AutoScroll = true;

                }

// I want to set the columnwidth of the layout so that when the labels are displayed they do not get clustered and look exactly like when displaying the checkboxes.How do I do it?

In general, what I do is:

  • Use the IDE in a 'prototype' project, to create a form with the controls in the positions that I want
  • Look at the source code created by the IDE (in the MyFormName .Designer.cs file) to see what source code is generated by the IDE to creat these controls
  • Create my own form in my real project, with hand-coded code that's based on what I learned from the prototype which I created using the IDE
// Loop through all the controls you want to add.
// Add a integer field that measures the highest width of each control like

int _iMaxWidth = 0;

for (int i=0; i < TotalControls.Count; ++i)
{
   if ( control[i].Width > _iMaxWidth)
      _iMaxWidth = control[i].Width
}

// Then you'll know what the width size of the column should be.
Col.Width = iMaxWidth + 2; // +2 to make things a little nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM