日期:2014-05-18  浏览次数:21159 次

C#被委托调用的方法如何知道是哪一个类调用了它?
这个问题是我在写一个gridview分页器的时候遇到的,这个分页器包括十几个linkbutton,我的思路是,linkbutton.onclick= "show_content(自己写的分页代码方法) ",show_content中是根据linkbutton的text属性,读取数据库中相应的记录,跳转到相应的页。如:
protected   show_content(object   sender,eventargs   e)
{
int   ipage=Convert.ToInt32(linkbutton.Text);
/*
关键是上面这句,怎么访问相应的linkbutton?用this.Text应该是不行的
吧,因为这个show_content函数是在另一个类里定义的,而不是linkbutton类的方法。
试过了object.ToString(),可是返回的是类名而不是对象名。
*/
get_data(ipage);
//绑定,填充。。。。
}

这个问题怎么解决?

------解决方案--------------------
在Form1.Designer.cs中有下面两段代码
this.button1.Location = new System.Drawing.Point(75, 59);
this.button1.Name = "button1 ";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1 ";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//

// button2
//
this.button2.Location = new System.Drawing.Point(75, 118);
this.button2.Name = "button2 ";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2 ";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
你只要把其中的
this.button1.Click += new System.EventHandler(this.button1_Click_1);
this.button2.Click += new System.EventHandler(this.button2_Click);
改成
this.button1.Click += new System.EventHandler(this.button1_Click_1);
this.button2.Click += new System.EventHandler(this.button1_Click);
然后在
private void button1_Click_1(object sender, EventArgs e)
{
if(((Button)sender).Text== "button1 ")
//
if(((button)sender).text== "button2 ")
//

}
就可以了
原理就是将所有按钮的委托中执行的函数都指定为同一个,然后在这个函数中判断是点击了哪个按钮,执行相应的操作