Condividi tramite


Procedura: Impostare il valore visualizzato dal controllo ProgressBar di Windows Form

Importante

Il controllo ToolStripProgressBar sostituisce e aggiunge funzionalità al controllo ProgressBar; Tuttavia, il controllo ProgressBar viene mantenuto sia per la compatibilità con le versioni precedenti che per l'uso futuro, se si sceglie.

.NET Framework offre diversi modi per visualizzare un determinato valore all'interno del controllo ProgressBar. 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.

Avvicinarsi Descrizione
Imposta direttamente il valore del controllo ProgressBar. Questo approccio è utile per le attività in cui si conosce la quantità complessiva dell'elemento misurato che verrà coinvolto, ad esempio la lettura dei record da una fonte di dati. Inoltre, se è sufficiente impostare il valore una o due volte, questo è un modo semplice per farlo. Infine, utilizzare questo processo se è necessario ridurre il valore visualizzato dalla barra di avanzamento.
Aumentare la visualizzazione ProgressBar in base a 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 il display ProgressBar di un valore variabile. 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 proprietà Value. Questa operazione può essere eseguita in fase di progettazione o in fase di esecuzione.

Per impostare direttamente il valore ProgressBar

  1. Impostare i valori di Minimum e Maximum del controllo ProgressBar.

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

    Nota

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

    Nell'esempio di codice seguente viene illustrato come impostare direttamente il valore ProgressBar. 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 form abbia un controllo Label, un controllo ProgressBar e una tabella dati con una riga denominata CustomerRow con campi FirstName 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 valore del controllo ProgressBar 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 la barra di progresso di un valore fisso

  1. Impostare i valori di Minimum e Maximum del controllo ProgressBar.

  2. Impostare la proprietà Step del controllo su un numero intero che rappresenta l'importo necessario per aumentare il valore visualizzato della barra di avanzamento.

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

    Nell'esempio di codice seguente viene illustrato come una barra di avanzamento 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 nel form sia presente un controllo Label e un controllo ProgressBar.

    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 una barra di avanzamento 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 la barra di avanzamento con un valore dinamico

  1. Impostare i valori di Minimum e Maximum del controllo ProgressBar.

  2. Per cambiare il valore visualizzato da un intero che hai specificato, chiama il metodo Increment.

    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 nel form sia presente un controllo Label e un controllo ProgressBar.

    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();  
       }  
    }  
    

Vedere anche