Динамическое добавление элементов windows forms

I just wrote a fast C# project in my visual studio. The code below adds a new textbox to the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox txtBox;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox();
            txtBox.Location = new Point(10, 50);
            txtBox.Visible = true;
            Controls.Add(txtBox);
        }
    }
}

——————————————ADDED————————————-

The code below, will add 4 textboxes and 4 labels, like you want it. You can see the picture(at the end of the code), how it shows on my example.

P.s.: You will need to configure the position properly though.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox[] txtBox;
        Label[] lbl;

        int n = 4;
        int space = 20;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox[n];
            lbl = new Label[n];

            for (int i = 0; i < n; i++)
            {
                txtBox[i] = new TextBox();
                txtBox[i].Name = "n" + i;
                txtBox[i].Text = "n" + i;

                lbl[i] = new Label();
                lbl[i].Name = "n" + i;
                lbl[i].Text = "n" + i;
            }


            for (int i = 0; i < n; i++)
            {
                txtBox[i].Visible = true;
                lbl[i].Visible = true;
                txtBox[i].Location = new Point(40, 50 + space);
                lbl[i].Location = new Point(10, 50 + space);
                this.Controls.Add(txtBox[i]);
                this.Controls.Add(lbl[i]);
                space += 50;
            }

        }
    }
}

Screenshot: http://shrani.si/f/1F/Y/22BgTuBX/example.png

I also took the time and uploaded the project i made to Sendspace.

Download link: http://www.sendspace.com/file/glc7h2

Последнее обновление: 31.10.2015

Для организации элементов управления в связанные группы существуют специальные элементы — контейнеры. Например, Panel, FlowLayoutPanel,
SplitContainer, GroupBox. Ту же форму также можно отнести к контейнерам. Использование контейнеров облегчает управление элементами, а также
придает форме определенный визуальный стиль.

Все контейнеры имеют свойство Controls, которое содержит все элементы данного контейнера. Когда мы переносим какой-нибудь
элемент с панели инструментов на контейнер, например, кнопку, она автоматически добавляется в данную коллекцию данного контейнера.
Либо мы также можем добавить элемент управления динамически с помощью кода в эту же коллекцию.

Динамическое добавление элементов

Добавим на форму кнопку динамически. Для этого добавим событие загрузки формы, в котором будет создаваться новый элемент управления.
Это можно сделать либо с помощью кода, либо визуальным образом.

С помощью перетаскивания элементов с Панели Инструментов мы можем легко добавить новые элементы на форму. Однако такой способ довольно ограничен,
поскольку очень часто требуется динамически создавать (удалять) элементы на форме.

Для динамического добавления элементов создадим обработчик события загрузки формы в файле кода:

private void Form1_Load(object sender, EventArgs e)
{
}

Теперь добавим в него код добавления кнопки на форму:

private void Form1_Load(object sender, EventArgs e)
{
    Button helloButton = new Button();
    helloButton.BackColor = Color.LightGray;
    helloButton.ForeColor = Color.DarkGray;
    helloButton.Location = new Point(10, 10);
    helloButton.Text = "Привет";
    this.Controls.Add(helloButton);
}

Сначала мы создаем кнопку и устанавливаем ее свойства. Затем, используя метод Controls.Add мы добавляем ее в коллекцию элементов
формы. Если бы мы это не сделали, мы бы кнопку не увидели, поскольку в этом случае для нашей формы ее просто не существовало бы.

С помощью метода Controls.Remove() можно удалить ранее добавленный элемент с формы:

this.Controls.Remove(helloButton);

Хотя в данном случае в качестве контейнера использовалась форма, но при добавлении и удалении элементов с любого другого контейнера, например,
GroupBox, будет применяться все те же методы.

I just wrote a fast C# project in my visual studio. The code below adds a new textbox to the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox txtBox;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox();
            txtBox.Location = new Point(10, 50);
            txtBox.Visible = true;
            Controls.Add(txtBox);
        }
    }
}

——————————————ADDED————————————-

The code below, will add 4 textboxes and 4 labels, like you want it. You can see the picture(at the end of the code), how it shows on my example.

P.s.: You will need to configure the position properly though.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox[] txtBox;
        Label[] lbl;

        int n = 4;
        int space = 20;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox[n];
            lbl = new Label[n];

            for (int i = 0; i < n; i++)
            {
                txtBox[i] = new TextBox();
                txtBox[i].Name = "n" + i;
                txtBox[i].Text = "n" + i;

                lbl[i] = new Label();
                lbl[i].Name = "n" + i;
                lbl[i].Text = "n" + i;
            }


            for (int i = 0; i < n; i++)
            {
                txtBox[i].Visible = true;
                lbl[i].Visible = true;
                txtBox[i].Location = new Point(40, 50 + space);
                lbl[i].Location = new Point(10, 50 + space);
                this.Controls.Add(txtBox[i]);
                this.Controls.Add(lbl[i]);
                space += 50;
            }

        }
    }
}

Screenshot: http://shrani.si/f/1F/Y/22BgTuBX/example.png

I also took the time and uploaded the project i made to Sendspace.

Download link: http://www.sendspace.com/file/glc7h2

I have come up with my own solution with your help and some research. I have implemented the Model View Controller Passive View so that no logic is handled in the View. I still have a few loose digits to clean up, but that was not the main focus.

In the View’s MouseUp event handler just two events are fired. One for the Presenter that will get data from the Model (that gets it from the database) which is passed to the User Control through the View, and one for the User Control to initialize itsself. The User Control is then added to the View.

View MouseUp event handler

// Fires the initializing user control and initializing user control data events.
private void questionStandardInput_MouseUp(object sender, MouseEventArgs e)
{
    InitializingUserControl?.Invoke(this, EventArgs.Empty);
    InitializingUserControlData?.Invoke(this, EventArgs.Empty);
}

User Control constructor and Initializing function

    // Initialize user control with IDetailScreenView. Subscribe to necessary events.
    public DetailScreenUserControl(IDetailScreenView view)
    {
        InitializeComponent();
        _view = view;
        _view.InitializingUserControl += InitializeUserControl;
    }

    // Initializes the user control for the detail screen.
    public void InitializeUserControl(object sender, EventArgs e)
    {
        List<string> qStandards = _view.SelectedQuestionStandards;
        Controls.Clear();
        maturityInput.Clear();
        complianceInput.Clear();

        int inputSeparation = 115;
        int secondInputX = 35;
        int inputHeight = 20;
        int labelWidth = 200;
        int inputWidth = 170;

        for (int  i = 0; i < qStandards.Count; i++)
        {
            Panel inputPanel = new Panel();
            inputPanel.Location = new Point(0, i * inputSeparation);
            inputPanel.AutoSize = true;
            inputPanel.BackColor = Color.AliceBlue;
            this.Controls.Add(inputPanel);

            Label qs_label = new Label();
            qs_label.Location = new Point(0, 0);
            qs_label.Font = new Font("Arial", 12F, FontStyle.Bold);
            qs_label.Size = new Size(labelWidth, inputHeight);
            qs_label.AutoSize = true;
            qs_label.Text = qStandards[i].ToString();
            inputPanel.Controls.Add(qs_label);

            Label m_label = new Label();
            m_label.Location = new Point(0, secondInputX);
            m_label.Font = new Font("Arial", 12F, FontStyle.Regular);
            m_label.Size = new Size(labelWidth, inputHeight);
            m_label.Text = "Maturity standard";
            inputPanel.Controls.Add(m_label);

            Label c_label = new Label();
            c_label.Location = new Point(0, secondInputX * 2);
            c_label.Font = new Font("Arial", 12F, FontStyle.Regular);
            c_label.Size = new Size(labelWidth, inputHeight);
            c_label.Text = "Compliance standard";
            inputPanel.Controls.Add(c_label);

            ComboBox m_input = new ComboBox();
            m_input.Location = new Point(labelWidth, secondInputX);
            m_input.Font = new Font("Arial", 10F, FontStyle.Regular);
            m_input.Size = new Size(inputWidth, inputHeight);
            m_input.DropDownStyle = ComboBoxStyle.DropDownList;
            maturityInput.Add(m_input);
            inputPanel.Controls.Add(m_input);

            ComboBox c_input = new ComboBox();
            c_input.Location = new Point(labelWidth, secondInputX * 2);
            c_input.Font = new Font("Arial", 10F, FontStyle.Regular);
            c_input.Size = new Size(inputWidth, inputHeight);
            c_input.DropDownStyle = ComboBoxStyle.DropDownList;
            complianceInput.Add(c_input);
            inputPanel.Controls.Add(c_input);

        }

        saveAssessmentButton.Location = new Point(195, qStandards.Count * inputSeparation);
        saveAssessmentButton.Size = new Size(130, 25);
        saveAssessmentButton.Text = "Save assessment";
        saveAssessmentButton.BackColor = SystemColors.ButtonHighlight;
        this.Controls.Add(saveAssessmentButton);

        _view.AddUserControl();
    }

Благодарю! Правда когда удаляешь последнюю строку и после этого еще раз нажимаешь удалить возникает проблема:

System.ArgumentOutOfRangeException не обработано
Message=Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.
Имя параметра: index
Source=mscorlib
ParamName=index
StackTrace:
в System.ThrowHelper.ThrowArgumentOutOfRangeException()
в System.Collections.Generic.List`1.get_Item(Int32 index)
в test2.Form1.удалитьСтрокуToolStripMenuItem_Click(Object sender, EventArgs e) в d:\Test\test2\Form1.cs:строка 50
в System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
в System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
в System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
в System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
в System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
в System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.ToolStrip.WndProc(Message& m)
в System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
в System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNat iveMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
в test2.Program.Main() в d:\Test\test2\Program.cs:строка 17
в System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException:

  • Диск без буквы windows 7
  • Динамики вместо наушников windows 10
  • Динамический диск или базовый windows 10
  • Динамические фоны для windows 10
  • Динамические темы для windows 11