我需要帮助来解决我的代码问题。我有3节课。 Class 1是一个带有Progressbar的WinForm。第2类是事件被触发的地方。第3类是进度的EventArg。该程序编译出任何错误,但当我单击按钮时,进度条不会移动!
namespace WindowsFormsApplication1
{
class Class1
{
//Declaring a delegate
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
//Declaraing an event
public event StatusUpdateHandler OnUpdateStatus;
public int recno;
public void Func()
{
//time consuming code
for (recno = 0; recno <= 100; recno++)
{
UpdateStatus(recno);
}
}
public void UpdateStatus(int recno)
{
// Make sure someone is listening to event
if (OnUpdateStatus == null) return; <--------------OnUpdateStatus is always null not sure why?
ProgressEventArgs args = new ProgressEventArgs(recno);
OnUpdateStatus(this, args);
}
}
}
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Class1 testClass;
public Form1()
{
InitializeComponent();
testClass = new Class1();
testClass.OnUpdateStatus += new Class1.StatusUpdateHandler(UpdateStatus);
}
public void button1_Click(object sender, EventArgs e)
{
Class1 c = new Class1();
c.Func();
}
public void UpdateStatus(object sender, ProgressEventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = e.Recno;
}
}
}
namespace WindowsFormsApplication1
{
public class ProgressEventArgs : EventArgs
{
public int Recno { get; private set; }
public ProgressEventArgs(int recno)
{
Recno = recno;
}
}
}
答案 0 :(得分:1)
您从未向c
的事件添加事件处理程序。
您确实为testClass
'事件添加了处理程序,但从未使用testClass
。
答案 1 :(得分:1)
您正在使用Class1的两个不同对象。
在按钮单击处理程序中,对象c
与成员对象testClass
不同。使用testClass
代替c
,它可以解决问题
public void button1_Click(object sender, EventArgs e)
{
testClass.Func();
}