统一处理同一网页下多个相同控件相同事件?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;
public partial class 主界面 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string temp= Process.UserNameString;
UserName.Text = Process.UserNameString;
foreach (Control PageCtrl in form1.Controls)
{
if (PageCtrl is LinkButton)
{
PageCtrl.Click += new EventHandler(LinkButton_Click);//这里说没有Click 为什么
}
}
}
void LinkButton_Click(object sender, EventArgs e)
{
((LinkButton)sender).Text = Process.RestaurantString;
Response.Redirect("食堂界面.aspx");
}
------解决方案--------------------
应该这样:
foreach (Control PageCtrl in form1.Controls)
{
if (PageCtrl is LinkButton)
{
LinkButton l = (LinkButton)PageCtrl;
l.Click += new EventHandler(LinkButton_Click);
}
}
------解决方案--------------------楼上正解,但是这样写我觉得比较好:
foreach (Control PageCtrl in form1.Controls)
{
if (PageCtrl is LinkButton)
{
LinkButton l = PageCtrl as LinkButton;
l.Click += new EventHandler(LinkButton_Click);
}
}