如何使动态创建的控件在单击时不会消失?

时间:2018-01-21 23:58:58

标签: c# asp.net dynamic-controls

当我按下它并为此控件定义Click事件处理程序时,我已经编写了一个代码隐藏(在c#中)来创建一个控件(ImageButton)。当我单击它时,如何强制此控件不会消失并触发其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); 
}

1 个答案:

答案 0 :(得分:0)

这是通过代码

添加控件的示例
// 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);
}