PDA

View Full Version : آموزش: اضافه کردن کنترل در زمان اجرا و مدیریت آنها



ایمان مدائنی
یک شنبه 03 شهریور 1392, 10:03 صبح
http://barnamenevisan.org/ImagesArticle/747fce64189a4ffb9afe3c533174c148.jpg


در این مقاله اضافه کردن کنترل در زمان اجرای برنامه به فرم و مدیریت رویدادهای آنها رو بررسی میکنیم



با زدن کلید اضافه یک Button و یک Lable و یک TextBox به فرم اضافه میشود

و با زدن کلید کنار هرکدام رویداد آن اجرا میشود

در مرحله اول از کنترل ها یک نمونه میسازیم و خواص آنها را ست میکنیم



Label label = new Label();
int count = panel1.Controls.OfType<Label>().ToList().Count;
label.Location = new Point(10, (25 * count) + 2);
label.Size = new Size(40, 20);
label.Name = "label_" + (count + 1);
label.Text = "label " + (count + 1);
panel1.Controls.Add(label);
TextBox textbox = new TextBox();
count = panel1.Controls.OfType<TextBox>().ToList().Count;
textbox.Location = new Point(60, 25 * count);
textbox.Size = new Size(80, 20);
textbox.Name = "textbox_" + (count + 1);
textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
panel1.Controls.Add(textbox);
Button button = new Button();
count = panel1.Controls.OfType<Button>().ToList().Count;
button.Location = new Point(150, 25 * count);
button.Size = new Size(60, 20);
button.Name = "button_" + (count + 1);
button.Text = "Button " + (count + 1);
button.Click += new System.EventHandler(this.Button_Click);

در مرحله بعد به فرم اضافه مکنیم

و رویداد ها رو هم در فرم تعریف میکنیم


private void TextBox_Changed(object sender, EventArgs e)
{
TextBox textbox = (sender as TextBox);
MessageBox.Show(textbox.Name + " text changed. Value " + textbox.Text);
}




private void Button_Click(object sender, EventArgs e)
{
Button button = (sender as Button);
MessageBox.Show(button.Name + " clicked");
}


نمونه ضمیمه شده است



موفق و پیروز باشید

منبع : Barnamenevisan.org (http://barnamenevisan.org/)