我正在使用foreach循环生成content如何监听按钮单击以调用代码隐藏功能。我无法为ASP按钮设置值。我该怎么办呢?当用户点击按钮时,我希望他们点击的用户的ID传递给代码隐藏
答案 0 :(得分:1)
您可以在按钮的CommandArgument属性中传递ID,并且可以在循环内部分配onclick事件:
//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
}
答案 1 :(得分:0)
您可以使用运行时生成的Button Id将值传递给它。
//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);
}