1

Good day i want to pass a value to a onclick button method :

This is my dynamically created button :

string Code = //Some value
Button button = new Button();
button.ID = "Start";
button.Click +=new EventHandler(button_Click);
button.CommandArgument = Code;
Page.Controls.Add(button);

this my event method :

 void button_Click(object sender, EventArgs e)
 {
     string code = //Put the value in code 
 }

Thanks.

2 Answers 2

5

One widely used approach is to save such values in a server accessible controls or variable.

In concrete words:

If you want to pass the dynamic value from client side, use an ASP:HiddenField, set its value using JavaScript and access in the server code

<asp:HiddenField runat="server" id="hfMyArgument" value="" />

you can use the value on server side

void button_Click(object sender, EventArgs e)
{
     string code = hfMyArgument.value.trim();
}

Create and use a session variable while creating the button

Session["MyArgument"] = "argument value";
Session["MySecondArgument"] = 143523;

to use these values on server side code C#

void button_Click(object sender, EventArgs e)
{
     string code = Convert.toString(Session["MyArgument"]).trim();
}
Sign up to request clarification or add additional context in comments.

1 Comment

my pleasure, and thanks for marking my answer helpful. if you don't need to take the argument from the client side and need to use something like global variable then session is a better approach, as you don't need to change the asp code to add the hidden field.
1

since you are using the CommandArgument property of button, you can access this property in OnCommand event of this button. [ But NOT in OnClick ]

So, define an event handler for OnCommand event as:

button.Command += new CommandEventHandler(button_Command); 

And in your event handler access the CommandArgument as:

void button_Command(object sender, CommandEventArgs e)
 {
     string _code = e.CommandArgument.ToString();
 } 

2 Comments

ive tried this but when i click the button it posts back.and the page is refreshed the event is not fired.
Make sure you create the controls every time you postback. The code creating the controls should not be inside(!IsPostBack) condition. And postback will happen. Do you want to avoid it ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.