Небольшой пример, демонстрирующий то, как создавать новые элементы управления окна на лету.
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);
}
}
}
Спасибо за статью:)
У вас ошибочка небольшая:
public static string btnCounter = 0; // счетчик кнопок
Наверно тут нужен int?:)
Да, спасибо, именно int)