2011-11-02 17 views
0

我需要疑難解答代碼的幫助。我有3個班。 1類是帶有進度條的WinForm。第2類是事件發生的地方。第3類是進展的EventArg。該程序沒有任何錯誤編譯,但是當我點擊按鈕時,進度條不會移動!C#進度條基於事件和delgate不工作

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

不要委託類型;相反,使用'EventHandler ' – SLaks

回答

1

您使用的Class1的兩個不同的對象。

在按鈕點擊事件處理中,對象是c不一樣的構件對象testClass。代替c使用testClass它shud工作

public void button1_Click(object sender, EventArgs e) 
{ 
    testClass.Func(); 
} 
1

您從未將事件處理程序添加到c的事件中。

你做了處理程序添加到testClass「事件,但從未使用過testClass

+0

可以請您進一步闡述。 – Shazam

+0

'c'和'testClass'具有兩個不同的事件並具有兩個不同的事件。你只把你的處理程序添加到其中的一個。 – SLaks