动态加载多个ascx并激发事件处理
ascx类中公开属性PhoneID用于区别不同的对象
//电话PhoneID
public int PhoneID
{
get { return _PhoneID; }
set { _PhoneID = value; }
}
自定义事件参数event类
//自定义事件参数event类
//public class PhoneItemEventArgs : EventArgs
//{
// private object _senderex;
// public object senderex
// {
// get
// {
// return _senderex;
// }
// }
// public PhoneItemEventArgs(object sender) : base()
// {
// this._senderex = sender;
// }
//}
//在ascx的类中添加事件定义代码
public event ItemCommandHandler OnCommand;
public delegate void ItemCommandHandler(object sender, PhoneItemEventArgs e);
//触发事件,可在其它按钮事件中调用
private void SendCommand(object sender, EventArgs e)
{
if (OnCommand != null)
{
OnCommand(this, new PhoneItemEventArgs(sender));
}
}
//按钮事件调用SendCommand,触发事件
//protected void lbtnNum_Click(object sender, EventArgs e)
//{
// SendCommand(sender, e);
//}
在调用 ascx的页面合适的位置,添加 PlaceHolder 控件做为动态加载的容器
<asp:PlaceHolder ID="PhoneList" runat="server" > </asp:PlaceHolder>
在后台代码(.cs)添加代码,动态加载控制
PhoneList.Controls.Add(new LiteralControl("<table><tr>"));
foreach (DataRow dr in dt.Rows)
{
if (i > 100) //限制100个
{
break;
}
PhoneID = i;
Inc_PhoneItem tmpItem = (Inc_PhoneItem)LoadControl("~/Inc/PhoneItem.ascx");
tmpItem.Visible = true;
tmpItem.ID = "PhoneItem" + PhoneID.ToString();
tmpItem.PhoneID = Convert.ToInt32(PhoneID);
//添加事件
tmpItem.OnCommand += new Inc_PhoneItem.ItemCommandHandler(this.PhoneItemCommand);
PhoneList.Controls.Add(tmpItem);
PhoneList.Controls.Add(new LiteralControl("<td>"));
PhoneList.Controls.Add(tmpItem);
PhoneList.Controls.Add(new LiteralControl("</td>"));
//每5列换行
if (i % 5 == 0)
{
PhoneList.Controls.Add(new LiteralControl("</tr>"));
PhoneList.Controls.Add(new LiteralControl("<tr>"));
}
i++;
}
PhoneList.Controls.Add(new LiteralControl("</tr></table>"));
在cs代码中添加事件处理过程
//private void PhoneItemCommand(Object sender, PhoneItemEventArgs e)
//{
// string commad = "";
// Inc_PhoneItem tmpItem = (Inc_PhoneItem)sender;
// if (e.senderex.GetType().Equals(typeof(LinkButton)))
// {
// LinkButton senderex = (LinkButton)e.senderex;
// commad = senderex.CommandName;
// }
// if(commad.Equals("Level") )
// {
// this.PanelLevel.Visible = true;
// }
// }