簡體   English   中英

如何使動態創建的控件在單擊時不消失?

[英]How to cause dynamically created controls not to disappear when clicked?

我已經為按鈕編寫了代碼隱藏(在c#中),以在按下按鈕時創建控件(ImageButton),並為此控件定義了Click事件處理程序。 當我單擊該控件時,如何強制它不消失並觸發其Click事件處理程序? 我希望通過單擊Button來創建控件,因此不能像其他答案中所建議的那樣在OnInit()方法中創建該控件。

protected void Button8_Click(object sender, EventArgs e) 
{ 
    Button btn = (Button)sender; 
    Control box = btn.Parent; 
    ImageButton lamp = new ImageButton(); 
    lamp.ID = "MyLamp"; lamp.ImageUrl = "grey_lamp.jpg"; 
    lamp.Style["Position"] = "absolute"; 
    lamp.Style["Top"] = "40px"; 
    lamp.Style["Left"] = "100px"; 
    lamp.Style["Height"] = "20px"; 
    lamp.Click += Image3_Click; 
    box.Controls.Add(lamp); 
    CreateNewTable(); 
    base.OnInit(e); 
}

這是通過代碼添加控件的示例

// the method; your button click method
private void ButtonClick() { 
   // create a new control
   // my example would be a button
   Button newButton = new Button();
   // the button's content
   newButton.Content = "Im a new button";
   // the click event listener
   newButton.Click += (_, __) => { // params: object sender, Clickeventargs
      // here should be the instructions of the button to perform when clicked
      Debug.Writeline("The new button has been clicked");
      // do some amazing stuffs
   }

   // add the button to the parent control; a grid or stachpanel, etc.
   someParentControl.Children.Add(newButton);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM