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
Asked
Active
Viewed 970 times
2 Answers
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
}

Bolo
- 1,494
- 1
- 19
- 19
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);
}

Sriprem rookie
- 39
- 1
- 2
- 12