I want to create dynamic buttons on button click event(for example., btnCreateDynamic_Click). I tried creating dynamic buttons on page_load event and Pre_int event.They are all working but i want to create them in button click event. How can i do this in c# asp.net?
+1
A:
Your button click event at the client will cause a page postback that will start the ASP.Net Page Life-cycle;
Your button click event on the server is a PostBackEvent and you should be able to use the same method call CreateMyButton()
that you used in the Load or Init events.
Dave Anderson
2010-10-27 11:42:12
A:
An idea would be to create a list of buttons in which you'd store the buttons you created in btnCreateDynamic_click.
you could have a method like:
private Button CreateButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Button_Click);
b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
return b;
}
in btnCreateDynamic_click you could have something like:
Button b = CreateButton("dinamicBtn"+myDinamicButtonsList.Count.ToString(),"dinamicBtn"+myDinamicButtonsList.Count.ToString());
myDinamicButtonsList.add(b);
and in the pageLoad for example you could do something like
foreach(button btn in myDinamicButtonsList){
form1.Controls.Add(btn));
}
List<Button> myDinamicButtonsList = new List<Button>();
myDinamicButtonsList should be stored somewhere from where it could be retrieved after each request.
EDIT: In page load you could have something like this:
if(Session["myDinamicButtons"] == null){
List<Button> myDinamicButtonsList = new List<Button>();
Session["myDinamicButtons"] = myDinamicButtonsList;
}
foreach(Button btn in Session["myDinamicButtons"] as List<Button>){
form1.Controls.Add(btn));
}
i didn't tested it but it should work.
SorinA.
2010-10-27 11:49:40
(As im not familier with list)Can i store the buttons in arraylist instead of List? I tried but i got error. Would you please help?
Prem
2010-10-27 13:15:07
you can create the list this: List<Button> myDinamicButtonsList = new List<Button>(); you have to think where you could store it in order to have access to it every time the page reloads. you could add it in a session variable like this Session["myDinamicButtonsList"] = myDinamicButtonsList; and retrieve it from there on each page load. just an idea..
SorinA.
2010-10-27 13:46:08
Thank you very much...!!! it works
Prem
2010-10-28 04:17:51