0

I'm using a foreach loop to generate content how do I listen for a button click to call codebehind function. I can't set a value for a ASP button. How should I go about this ? When the user clicks on a button I want the ID for the user they clicked on to get passed to codebehind

2 Answers 2

1

You can pass the ID in the CommandArgument property of a button and you can assign the onclick event all inside the loop:

//for loop
//...
Button btn = new Button();
//etc
btn.CommandArgument = theID;
btn.Click += new EventHandler(btn_Click);
//...
//end for loop

protected void btn_Click(object sender, EventArgs e)
{
    //Need to know which btn was clicked
    Button btn = sender as Button;
    if(btn == null)
    {
        //throw exception, etc
    }
    int id = Convert.ToInt32(btn.CommandArgument);
    //etc
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Runtime generated Button Id to pass values to it.

//Counter for Dynamic Buttons.
int DynamicButtonCount = 1;

//This event generates Dynamic Buttons.
private void btnGenerate_Click(object sender, EventArgs e)
{
    string name = "Dynamic Button_" + DynamicButtonCount;
    Button btnDynamicButton = new Button();
    btnDynamicButton.Name = name;
    btnDynamicButton.Text = name;
    btnDynamicButton.Id=  DynamicButtonCount; //Use this id value
    btnDynamicButton.Size = new System.Drawing.Size(200, 30);
    btnDynamicButton.Location = new System.Drawing.Point(40, DynamicButtonCount * 40);
    btnDynamicButton.Click += new EventHandler(this.btnDynamicButton_Click);
    Controls.Add(btnDynamicButton);
    DynamicButtonCount++;
}

//This event is triggered when a Dynamic Button is clicked.
protected void btnDynamicButton_Click(object sender, EventArgs e)
{
    Button dynamicButton = (sender as Button);
    MessageBox.Show("You clicked. " + dynamicButton.Name);
}

Comments

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.