Procedura: impostare il valore visualizzato da un controllo ProgressBar Windows Form

Importante

Benché il controllo ToolStripProgressBar sostituisca il controllo ProgressBar aggiungendovi funzionalità, il controllo ProgressBar viene mantenuto per compatibilità con le versioni precedenti e per un eventuale uso futuro.

.NET Framework offre diversi modi per visualizzare un determinato valore all'interno del ProgressBar controllo. L'approccio scelto dipenderà dall'attività a portata di mano o dal problema che si risolve. La tabella seguente illustra gli approcci che è possibile scegliere.

Approccio Descrizione
Impostare direttamente il valore del ProgressBar controllo. Questo approccio è utile per le attività in cui si conosce il totale dell'elemento misurato che verrà coinvolto, ad esempio la lettura di record da un'origine dati. Inoltre, se è sufficiente impostare il valore una o due volte, questo è un modo semplice per farlo. Usare infine questo processo se è necessario ridurre il valore visualizzato dall'indicatore di stato.
Aumentare la ProgressBar visualizzazione di un valore fisso. Questo approccio è utile quando si visualizza un conteggio semplice tra il numero minimo e il massimo, ad esempio il tempo trascorso o il numero di file elaborati da un totale noto.
Aumentare la ProgressBar visualizzazione in base a un valore che varia. Questo approccio è utile quando è necessario modificare il valore visualizzato un numero di volte in quantità diverse. Un esempio mostra la quantità di spazio su disco rigido utilizzato durante la scrittura di una serie di file sul disco.

Il modo più diretto per impostare il valore visualizzato da una barra di stato consiste nell'impostare la Value proprietà . Questa operazione può essere eseguita in fase di progettazione o in fase di esecuzione.

Per impostare direttamente il valore ProgressBar

  1. Impostare i valori e Maximum del MinimumProgressBar controllo.

  2. Nel codice impostare la proprietà del Value controllo su un valore intero compreso tra i valori minimo e massimo stabiliti.

    Nota

    Se si imposta la Value proprietà al di fuori dei limiti stabiliti dalle Minimum proprietà e Maximum , il controllo genera un'eccezione ArgumentException .

    Nell'esempio di codice seguente viene illustrato come impostare direttamente il ProgressBar valore. Il codice legge i record da un'origine dati e aggiorna la barra di stato e l'etichetta ogni volta che un record di dati viene letto. In questo esempio è necessario che il modulo abbia un Label controllo, un ProgressBar controllo e una tabella dati con una riga denominata CustomerRow con FirstName i campi e LastName .

    Public Sub CreateNewRecords()  
       ' Sets the progress bar's Maximum property to  
       ' the total number of records to be created.  
       ProgressBar1.Maximum = 20  
    
       ' Creates a new record in the dataset.  
       ' NOTE: The code below will not compile, it merely  
       ' illustrates how the progress bar would be used.  
       Dim anyRow As CustomerRow = DatasetName.ExistingTable.NewRow  
       anyRow.FirstName = "Stephen"  
       anyRow.LastName = "James"  
       ExistingTable.Rows.Add(anyRow)  
    
       ' Increases the value displayed by the progress bar.  
       ProgressBar1.Value += 1  
       ' Updates the label to show that a record was read.  
       Label1.Text = "Records Read = " & ProgressBar1.Value.ToString()  
    End Sub  
    
    public void createNewRecords()  
    {  
       // Sets the progress bar's Maximum property to  
       // the total number of records to be created.  
       progressBar1.Maximum = 20;  
    
       // Creates a new record in the dataset.  
       // NOTE: The code below will not compile, it merely  
       // illustrates how the progress bar would be used.  
       CustomerRow anyRow = DatasetName.ExistingTable.NewRow();  
       anyRow.FirstName = "Stephen";  
       anyRow.LastName = "James";  
       ExistingTable.Rows.Add(anyRow);  
    
       // Increases the value displayed by the progress bar.  
       progressBar1.Value += 1;  
       // Updates the label to show that a record was read.  
       label1.Text = "Records Read = " + progressBar1.Value.ToString();  
    }  
    

    Se si visualizza lo stato di avanzamento in base a un intervallo fisso, è possibile impostare il valore e quindi chiamare un metodo che aumenta il ProgressBar valore del controllo in base a tale intervallo. Ciò è utile per i timer e altri scenari in cui non si misura lo stato di avanzamento come percentuale dell'intero.

Per aumentare l'indicatore di stato di un valore fisso

  1. Impostare i valori e Maximum del MinimumProgressBar controllo.

  2. Impostare la proprietà del Step controllo su un numero intero che rappresenta l'importo per aumentare il valore visualizzato dell'indicatore di stato.

  3. Chiamare il PerformStep metodo per modificare il valore visualizzato dall'importo impostato nella Step proprietà .

    Nell'esempio di codice seguente viene illustrato come un indicatore di stato può mantenere un conteggio dei file in un'operazione di copia.

    Nell'esempio seguente, poiché ogni file viene letto in memoria, l'indicatore di stato e l'etichetta vengono aggiornati in modo da riflettere i file totali letti. In questo esempio è necessario che il form abbia un Label controllo e un ProgressBar controllo .

    Public Sub LoadFiles()  
       ' Sets the progress bar's minimum value to a number representing  
       ' no operations complete -- in this case, no files read.  
       ProgressBar1.Minimum = 0  
       ' Sets the progress bar's maximum value to a number representing  
       ' all operations complete -- in this case, all five files read.  
       ProgressBar1.Maximum = 5  
       ' Sets the Step property to amount to increase with each iteration.  
       ' In this case, it will increase by one with every file read.  
       ProgressBar1.Step = 1  
    
       ' Dimensions a counter variable.  
       Dim i As Integer  
       ' Uses a For...Next loop to iterate through the operations to be  
       ' completed. In this case, five files are to be copied into memory,  
       ' so the loop will execute 5 times.  
       For i = 0 To 4  
          ' Insert code to copy a file  
          ProgressBar1.PerformStep()  
          ' Update the label to show that a file was read.  
          Label1.Text = "# of Files Read = " & ProgressBar1.Value.ToString  
       Next i  
    End Sub  
    
    public void loadFiles()  
    {  
       // Sets the progress bar's minimum value to a number representing  
       // no operations complete -- in this case, no files read.  
       progressBar1.Minimum = 0;  
       // Sets the progress bar's maximum value to a number representing  
       // all operations complete -- in this case, all five files read.  
       progressBar1.Maximum = 5;  
       // Sets the Step property to amount to increase with each iteration.  
       // In this case, it will increase by one with every file read.  
       progressBar1.Step = 1;  
    
       // Uses a for loop to iterate through the operations to be  
       // completed. In this case, five files are to be copied into memory,  
       // so the loop will execute 5 times.  
       for (int i = 0; i <= 4; i++)  
       {  
          // Inserts code to copy a file  
          progressBar1.PerformStep();  
          // Updates the label to show that a file was read.  
          label1.Text = "# of Files Read = " + progressBar1.Value.ToString();  
       }  
    }  
    

    Infine, è possibile aumentare il valore visualizzato da un indicatore di stato in modo che ogni aumento sia un importo univoco. Ciò è utile quando si tiene traccia di una serie di operazioni univoche, ad esempio la scrittura di file di dimensioni diverse in un disco rigido o la misurazione dello stato di avanzamento come percentuale dell'intero.

Per aumentare l'indicatore di stato di un valore dinamico

  1. Impostare i valori e Maximum del MinimumProgressBar controllo.

  2. Chiamare il Increment metodo per modificare il valore visualizzato da un numero intero specificato.

    Nell'esempio di codice seguente viene illustrato come un indicatore di stato può calcolare la quantità di spazio su disco usata durante un'operazione di copia.

    Nell'esempio seguente, poiché ogni file viene scritto nel disco rigido, la barra di stato e l'etichetta vengono aggiornate in modo da riflettere la quantità di spazio su disco rigido disponibile. In questo esempio è necessario che il form abbia un Label controllo e un ProgressBar controllo .

    Public Sub ReadFiles()  
       ' Sets the progress bar's minimum value to a number
       ' representing the hard disk space before the files are read in.  
       ' You will most likely have to set this using a system call.  
       ' NOTE: The code below is meant to be an example and  
       ' will not compile.  
       ProgressBar1.Minimum = AvailableDiskSpace()  
       ' Sets the progress bar's maximum value to a number
       ' representing the total hard disk space.  
       ' You will most likely have to set this using a system call.  
       ' NOTE: The code below is meant to be an example
       ' and will not compile.  
       ProgressBar1.Maximum = TotalDiskSpace()  
    
       ' Dimension a counter variable.  
       Dim i As Integer  
       ' Uses a For...Next loop to iterate through the operations to be  
       ' completed. In this case, five files are to be written to the disk,  
       ' so it will execute the loop 5 times.  
       For i = 1 To 5  
          ' Insert code to read a file into memory and update file size.  
          ' Increases the progress bar's value based on the size of
          ' the file currently being written.  
          ProgressBar1.Increment(FileSize)  
          ' Updates the label to show available drive space.  
          Label1.Text = "Current Disk Space Used = " &_
          ProgressBar1.Value.ToString()  
       Next i  
    End Sub  
    
    public void readFiles()  
    {  
       // Sets the progress bar's minimum value to a number
       // representing the hard disk space before the files are read in.  
       // You will most likely have to set this using a system call.  
       // NOTE: The code below is meant to be an example and
       // will not compile.  
       progressBar1.Minimum = AvailableDiskSpace();  
       // Sets the progress bar's maximum value to a number
       // representing the total hard disk space.  
       // You will most likely have to set this using a system call.  
       // NOTE: The code below is meant to be an example
       // and will not compile.  
       progressBar1.Maximum = TotalDiskSpace();  
    
       // Uses a for loop to iterate through the operations to be  
       // completed. In this case, five files are to be written  
       // to the disk, so it will execute the loop 5 times.  
       for (int i = 1; i<= 5; i++)  
       {  
          // Insert code to read a file into memory and update file size.  
          // Increases the progress bar's value based on the size of
          // the file currently being written.  
          progressBar1.Increment(FileSize);  
          // Updates the label to show available drive space.  
          label1.Text = "Current Disk Space Used = " + progressBar1.Value.ToString();  
       }  
    }  
    

Vedi anche