Динамическое создание контролов

Небольшой пример, демонстрирующий то, как создавать новые элементы управления окна на лету.

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 dynamic_btn
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }
 public static int btnCounter = 0; // счетчик кнопок
 private void Form1_MouseDown(object sender, MouseEventArgs e)
 {
 Button bt = new Button(); // Создаем новую кнопку.
 bt.Size = new Size(80, 30); // Указываем размер кнопки
 bt.Location = new Point(e.X, e.Y); // и ее расположение
 bt.Text = "New Button " + btnCounter.ToString(); // Задаем текст новой кнопки.
 bt.Click += new System.EventHandler(newButton_Click); // Задаем обработчик события Click
 Controls.Add(bt); // Добавляем кнопку на форму
 btnCounter++;
 }
 private void newButton_Click(object sender, System.EventArgs e)
 {
 	 Button currentButton = (Button)sender; // проверяем, какая кнопка нажата
 MessageBox.Show("Hello, world from " + currentButton.Text);
 }
 }
}

Поблагодарить автора

2 Responses to Динамическое создание контролов

  1. Спасибо за статью:)

    У вас ошибочка небольшая:

    public static string btnCounter = 0; // счетчик кнопок

    Наверно тут нужен int?:)

Оставить комментарий

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>