2017-07-26 19 views
0
  1. 我在Visual Studio(版本2010)中工作。
  2. 我想在一種形式(不同的名稱空間和類)基於另一個名稱空間和類中的變量設置進度條。您在代碼中看到的ProgressPerc變量來自另一個類(我已經使用'OtherNameSpace'指出了它。)
  3. 它告訴我我無法將ProgressPerc轉換爲int(因爲我無法將類型轉換爲int)。

什麼會在這裏是最優化的解決方案,我想用這個變量來表示模擬的進度在兩個不同類別之間使用後臺工作的進度條

編輯:。加入ALMBerekeningen碼這是它只是一小部分,完整的代碼在這裏顯示太多了。

謝謝!


public class ALMBerekeningen 
{ 
    public int sim; 
    public int Progress; 
    public double ProgressPerc; 

    this.ProgressPerc = this.sim/1000; 
    this.Progress = (int)Math.Round(this.Progress * 100f, 0, MidpointRounding.AwayFromZero); 
} 

Public class Form1: Form 
{ 
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 

     ALMBerekeningen ProgressPerc; 

     int sims; 

     sims = (int)ProgressPerc; 

     try 
     { 
      backgroundWorker1.ReportProgress(sims); 
     } 

     catch (Exception ex) 
     { 
      backgroundWorker1.CancelAsync(); 
      MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     progressBar1.Value = e.ProgressPercentage; 
     lblProgress.Text = "Completed " + progressBar1.Value.ToString() + " %"; 
     progressBar1.Update(); 
    } 
} 
+0

@Mong Zhu我加了一部分代碼。 this.sim在ALMBerekeningen中更改並從1變爲1000. – RobinL

回答

1

您需要的ALMBerekeningen到後臺工作實例來傳遞,當您啓動它,然後在事件處理程序使用DoWorkEventArgs.Argument屬性來訪問它:

public void Main() 
{ 
    //The instance of the class with the variable for your progress bar 
    ALMBerekeningen almBerekeningen = new ALMBerekeningen(); 

    BackgroundWorker bgw = new BackgroundWorker(); 
    bgw.DoWork += bgw_DoWork; 

    //Pass your class instance in here 
    bgw.RunWorkerAsync(almBerekeningen); 
} 


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 

    //e.Argument is the instance of the class you passed in 
    var progressPerc = (ALMBerekeningen)e.Argument; 

    int sims; 

    sims = progressPerc.ProgressPerc; 

    try 
    { 
     backgroundWorker1.ReportProgress(sims); 
    } 

    catch (Exception ex) 
    { 
     backgroundWorker1.CancelAsync(); 
     MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 

順便說一句,你的所示的DoWork處理程序將只執行一次。爲了這個例子,我認爲你已經簡化了它。

+0

也許值得注意的是,複製的catch塊並不理想。 – vasek

+0

「您需要將ALMBerekeningen實例傳遞給後臺工作者」,您並不需要這麼做,如果它是「Form」類中的簡單字段,它也可以工作。 –