Click here to Skip to main content
15,887,812 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a document, with an ID (which i need). i am wanting to dynamically create a asp:Button control, that when clicked will trigger an event to then navigate the page to another URL with a query string of id= [documentID]

so how do i attach data (the documentId) to the dynamically created button, so when it clicks this information can be accessed from the event triggered? Any other ways of doing this are grateful too, i need to do this in C#, and normally i'd do it all in Javascript, so i'm a bit new.

Many Thanks
Posted

1 solution

You can use CommandArgument to store the value, then get it back from the sender on the click event.

C#
protected void Page_Load(object sender, EventArgs e)
       {
           Button b = new Button();
           b.ID = "btnTest";
           b.CommandArgument = "42";
           b.Click += new EventHandler(btnTest_Click);
           b.Text = "clickme";
           placeholder.Controls.Add(b);
       }

       protected void btnTest_Click(object sender, EventArgs e)
       {
           var button = (Button)sender;
           throw new Exception(button.CommandArgument.ToString());
       }
 
Share this answer
 
Comments
Grant Weatherston 12-Mar-14 6:34am    
i've done this but its not firing the event, it just refreshes the page (postsback) its not actually running the event i assigned to the button.
Shelby Robertson 12-Mar-14 9:53am    
Can you post your code?
Grant Weatherston 12-Mar-14 9:56am    
its ok i've fixed it, i've added the dynamic button creating to the page_init method
Shelby Robertson 12-Mar-14 9:58am    
ah, life cycle issue. Good Work!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900