我试图创建一个列表,其中每一行都有自己的删除按钮。
private Button createDeleteButton()
{
int rowToDelete = ctr;
Button deleteBtn = new Button();
deleteBtn.Text = "x";
deleteBtn.Click += new EventHandler(RemoveRow(rowToDelete));
return deleteBtn;
}
protected void RemoveRow(int specificRow)
{
TableRow rw = table.Rows[specificRow];
table.Rows.Remove(rw);
ctr--;
Session["table"] = table;
ViewState["ctr"] = ctr;
}
然而,我得到错误"方法未定义"在
中的RemoveRow(rowToDelete)上 deleteBtn.Click += new EventHandler(RemoveRow(rowToDelete));
有什么想法吗?
答案 0 :(得分:1)
这将为你做到这一点。
private void Form1_Load(object sender, EventArgs e)
{
int rowToDelete = 1;
Button deleteBtn = new Button();
deleteBtn.Text = "x";
deleteBtn.Click += (snd, evtargs) => { RemoveRow(snd, evtargs, rowToDelete); };
}
private void RemoveRow(object sender, EventArgs e, int index)
{
//your code
}
答案 1 :(得分:0)
使用闭包来捕获rowToDelete
变量。
deleteBtn.Click += (s, e) => RemoveRow(rowToDelete);
但要注意,这可能会导致内存泄漏,因为您没有取消订阅事件。