![](/img/trans.png)
[英]How can i create dynamic buttons on button click event (C sharp ASP.NET)?
[英]How can I create a dynamic button click event on a dynamic button?
我正在動態地在頁面上創建一個按鈕。 現在我想在該按鈕上使用按鈕單擊事件。
如何在 C# ASP.NET 中做到這一點?
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
對新手來說比較容易:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
只需在創建按鈕時將事件處理程序添加到按鈕。
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
這樣做要容易得多:
Button button = new Button();
button.Click += delegate
{
// Your code
};
您可以通過簡單的方式創建按鈕,例如:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
但是事件可能不會觸發,因為必須在每次回發時重新創建元素/元素,否則您將丟失事件處理程序。
我嘗試了這個解決方案來驗證 ViewState 已經生成並在每次回發時重新創建元素,
例如,假設您在單擊事件時創建按鈕:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
在回發時,例如在頁面加載時,您應該這樣做:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
在 CreateDynamicElements() 中,您可以放置您需要的所有元素,例如您的按鈕。
這對我來說效果很好。
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
假設您有 25 個對象並希望一個進程處理任何一個對象的單擊事件。 您可以編寫 25 個委托或使用循環來處理單擊事件。
public form1()
{
foreach (Panel pl in Container.Components)
{
pl.Click += Panel_Click;
}
}
private void Panel_Click(object sender, EventArgs e)
{
// Process the panel clicks here
int index = Panels.FindIndex(a => a == sender);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.