Adam92
Adam92

Reputation: 436

Create ASP Button Dynamically with Arguements Passed

Im trying to create a set of ASP C# buttons dynamically, which all call the same event on click, which I am able to implement fine like so....

Button updateClientPriceButton = new Button();
updateClientPriceButton.ID = "bttnUpdatePrice_" + row["company_name"].ToString();
updateClientPriceButton.Text = "Update";
updateClientPriceButton.Click += new System.EventHandler(updateClientPriceButton_Click);

With...

protected void updateClientPriceButton_Click(object sender, EventArgs e)
{
    // Do something
}

But how do I send an arugment in the type of string to this function also? I have tried..

updateClientPriceButton.Click += new System.EventHandler(updateClientPriceButton_Click(object, EventArgs, "test_value"));

Thanks for any help!

Upvotes: 0

Views: 48

Answers (1)

Andrei
Andrei

Reputation: 56688

This is not possible with the Click event. However Button has a Command event for this purpose:

updateClientPriceButton.Command += new System.EventHandler(updateClientPriceButton_Command);
updateClientPriceButton.CommandName = "SomeName";
updateClientPriceButton.CommandArgument = "test_value";

And the handler should look like this:

protected void updateClientPriceButton_Command(object sender, CommandEventArgs e)
{
    // Do something with e.CommandName and e.CommandArgument
}

The other way is to create you own control inheriting from Button with special event based on Button.Click and with special arguments. But having Command in place this seems to be an overhead here.

Upvotes: 2

Related Questions