![](/img/trans.png)
[英]How to Use Dynamically Created Button/textBox in C# Windows Forms?
[英]How to change dynamically created label text on dynamically created button click in C# Windows Forms application
我正在嘗試動態創建一些標簽和按鈕。 我想在動態創建的按鈕單擊時更改標簽的名稱。 在編寫button_click方法時,無法直接訪問label object。 我怎樣才能做到這一點?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DemoPanel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
int lblYVal = 10;
int btnYVal = 50;
for(int i = 1; i< 5; i++)
{
Label lbl = new Label();
lbl.Text = "test";
lbl.Name = "test"+i.ToString();
lbl.Location = new System.Drawing.Point(10, lblYVal);
lbl.Visible = true;
Button btn = new Button();
btn.Text = "Click";
btn.Name = "textBtn" + i.ToString();
btn.Location = new System.Drawing.Point(10,btnYVal);
btn.Visible = true;
btn.Click += new EventHandler(this.btn_click);
this.Controls.Add(lbl);
this.Controls.Add(btn);
lblYVal += 70;
btnYVal += 70;
}
}
void btn_click(object sender, EventArgs e)
{
//How can i change label text from here.
//lbl.text //Does Not exist Error.
Label lbl = new Label();
lbl.Text = "New text"; //Not changing Label text
}
}
}
您編寫的for
循環知道按鈕和 label。 您可以利用它編寫一個單擊處理程序來捕獲 label。 就像改變一樣簡單:
btn.Click += new EventHandler(this.btn_click);
至
btn.Click += (sender, args) => lbl.Text = "Clicked";
您可以維護標簽的按鈕字典,並使用它來查找匹配的 label。 另一種選擇是將索引與按鈕和 label 相關聯,並找到 label 。
我將向您說明字典選項。
Dictionary<Button, Label> mapping = new Dictionary<Button, Label>();
...
在你的循環中,
mapping[btn] = lbl;
在您的處理程序中,
((Label)mapping[(Button)sender)]).Text = "some text";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.