动态添加控件委托的问题
我在页面加一个Panel
<body>
<form id= "form1 " runat= "server ">
<div>
<asp:Panel ID= "Panel1 " runat= "server " Height= "50px " Width= "125px ">
</asp:Panel>
</div>
</form>
</body>
然后在cs文件里面动态添加LinkButton
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LinkButton[] lb = new LinkButton[4];
for (int i = 0; i < 4; i++)
{
lb[i] = new LinkButton();
lb[i].Text = "这是动态添加的LinkButton "+i.ToString();
lb[i].Click+=new EventHandler(MyClick);//委托
Panel1.Controls.Add(lb[i]);
}
}
private void MyClick(object sender, EventArgs e)
{
Response.Write( "在这里实现某种功能 ");
Response.Write( "在这里要能获得是第几个LinkButton ");
Response.Write( "是不是可以传递那个i ");
}
}
我这里是用委托实现动态添加的LinkButton的Click事件,但是我需要在MyClick()方法里面传一个我需要的参数,比如说上面for循环里面的i,怎么实现??跪求方法,真的感觉好难搞。。。
------解决方案--------------------MyClick是回调函数,参数不是你传进去的,是LinkButton在响应事件的时候传给你的,你不要把方向搞反了
------解决方案--------------------protected void Page_Load(object sender, EventArgs e)
{
LinkButton[] lb = new LinkButton[4];
for (int i = 0; i < 4; i++)
{
lb[i] = new LinkButton();
lb[i].ID = "lb " + i.ToString();
lb[i].Text = "这是动态添加的LinkButton " + i.ToString();
lb[i].Click += new EventHandler(MyClick);//委托
Panel1.Controls.Add(lb[i]);
}
}
private void MyClick(object sender, EventArgs e)
{
LinkButton l = (LinkButton)sender;
Response.Write(l.ID);
}
可以用l.ID.Substring 得到你要的i