创建C#winform简单动态控件

时间:2009-01-12 00:25:03

标签: c# winforms

        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;

                }

//我想设置布局的列宽,以便在显示标签时,它们不会聚集,看起来与显示复选框时完全一样。我该怎么做?

2 个答案:

答案 0 :(得分:4)

一般来说,我所做的是:

  • 在“原型”项目中使用IDE,创建一个控件位于我想要的位置
  • 查看IDE创建的源代码(在 MyFormName .Designer.cs文件中),以查看IDE生成哪些源代码以创建这些控件
  • 在我的真实项目中创建自己的表单,手工编码的代码基于我从使用IDE创建的原型中学到的内容

答案 1 :(得分:0)

// 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.
相关问题