给你两个例子你看下, 你把ispostback去掉试一下, 为空多部分表示页面回传的问题。
例子一:
[C#] 纯文本查看 复制代码 //声明事件委托
public delegate void ToolClickEventHandler(Object sender, EventArgs e);
//定义事件
public event ToolClickEventHandler ToolBtnClick;
//监视事件
protected void OnToolClick(Object sender, EventArgs e)
{
if (ToolBtnClick != null)
{
ToolBtnClick(sender, e);
}
}
private static System.Web.UI.WebControls.Button New;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < btnNum; i++)
{
New = new Button();
New.Text = arrayBtnText[i];
New.ID = "btnNew"+i.ToString();
//页面回传时点击事件委托无效
//New.Click += new System.EventHandler(btnNew_Click);
//动态产生的按钮,页面不能保存他的状态,页面回传时就没有了,缓存起来,页面回传时重新加载
if(btnCssClass!=null)
{
New.CssClass = btnCssClass;
}
Cache["New"+i.ToString()] = New;
}
}
if (panelCssClass != null)
{
Panel1.CssClass = panelCssClass;
}
Panel1.Controls.Clear();
for (int j = 0; j < btnNum;j++ )
if (Cache["New" + j.ToString()] != null)
{
Button old = (Button)Cache["New" + j.ToString()];
//一下这两个属性本应该是在具体应用程序中去设置,但因为这两个按钮的这两个属性具有一般性
//所以就在这里进行设置
if (old.Text != "提交" && old.Text != "保存")
{
old.CausesValidation = false;
}
if (old.Text == "删除" || old.Text=="清除")
{
old.Attributes.Add("onclick", "javascript:return confirm('Are you sure to delete?');");
}
old.Click += new System.EventHandler(btnNew_Click);
Panel1.Controls.Add((Control)Cache["New" + j.ToString()]);
}
}
public void btnNew_Click(Object sender, EventArgs e)
{
//Button btn = (Button)sender;
//str = btn.ID;
//Response.Write("<script>alert('"+str+"')</script>");
OnToolClick(sender, e);
}
例子二:
[C#] 纯文本查看 复制代码 using System;
public class MyClass
{
public static void Main()
{
PrintStr myPrinter = new PrintStr();
PrintHandler myHandler = null;
myHandler += new PrintHandler(myPrinter.CallPrint); // 将委托链接到方法,来实例化委托
if(myHandler!=null)
myHandler("Hello World!"); // 调用委托,相当于匿名调用委托所链接的方法
Console.Read();
}
}
public delegate void PrintHandler(string str); // 声明委托类型
public class PrintStr
{
public void CallPrint(string input)
{
Console.WriteLine(input);
}
}
有问题再跟帖
|