LinkButton.OnClick 带参数的方法
LinkButton.OnClick Method with Parameter
我正在 ASP.net 上动态创建一个 linkButton。我在单击 linkButton 时需要帮助,它会将 linkbutton 名称存储到我的 Label1(仅作为示例)。
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += new EventHandler(DynamicClick);
this.form1.Controls.Add(link);
}
}
//when I click the buttonLink
public void DynamicClick(object sender, EventArgs e)
{
//label1.text will get the .text of the button that i pressed
Label1.Text = "";
}
我会那样做
public void DynamicClick(object sender, EventArgs e)
{
LinkButton linkButton = sender as LinkButton;
if (linkButton != null)
{
Label1.Text = linkButton.Text;
}
}
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += delegate { Label1.Text = link.ID; };
this.form1.Controls.Add(link);
}
}
我会稍微改变 Valeh 的回答。
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += (s, ea) =>
{
Label1.Text = link.Text;
};
this.form1.Controls.Add(link);
}
}
创建一个单独的方法 public void DynamicClick(object sender, EventArgs e)
- 特别是 public
- 在没有必要时是一件坏事,因为它会破坏封装。当我们与设计师一起工作时,这样做是完全可以理解的,但是当我们自己编写代码时,这是一个坏主意。
我正在 ASP.net 上动态创建一个 linkButton。我在单击 linkButton 时需要帮助,它会将 linkbutton 名称存储到我的 Label1(仅作为示例)。
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += new EventHandler(DynamicClick);
this.form1.Controls.Add(link);
}
}
//when I click the buttonLink
public void DynamicClick(object sender, EventArgs e)
{
//label1.text will get the .text of the button that i pressed
Label1.Text = "";
}
我会那样做
public void DynamicClick(object sender, EventArgs e)
{
LinkButton linkButton = sender as LinkButton;
if (linkButton != null)
{
Label1.Text = linkButton.Text;
}
}
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += delegate { Label1.Text = link.ID; };
this.form1.Controls.Add(link);
}
}
我会稍微改变 Valeh 的回答。
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += (s, ea) =>
{
Label1.Text = link.Text;
};
this.form1.Controls.Add(link);
}
}
创建一个单独的方法 public void DynamicClick(object sender, EventArgs e)
- 特别是 public
- 在没有必要时是一件坏事,因为它会破坏封装。当我们与设计师一起工作时,这样做是完全可以理解的,但是当我们自己编写代码时,这是一个坏主意。