Progress bar for procedure stored in c# windows form

Asked

Viewed 53 times

1

I have a project that updates data through a stored procedure (delete, Insert, update) with a long duration not determined. I would like to present a progress bar with time not determined during the execution period of the procedure. I have no experience in progress bar. Can anyone explain how to implement?

private void btActualizar_Click(object sender, EventArgs e)
{
    _IDSave = _ID;
    _CartaoSave = _Cartao;

    // Chama o form onde se escolhe o ano de Contabilidade (cada ano um database!)
    frmEscolhaDeAnoContabilidade frmRefresh = new frmEscolhaDeAnoContabilidade();
    frmRefresh.ShowDialog();

    string dataBaseName = frmRefresh.dataBaseName;
    string anoContabilidade = frmRefresh.anoContabilidade;

    if (dataBaseName.Length > 0)
    {
        string timeRefresh; 
        string deletedRec;
        string newRec;
        string updatedRec;
        string errorMessage;

        string resultText;

        // Tornar visivel e por a funcionar a barra de progresso
        progressBarRefresh.Visible = true;

        progressBarAdatfrissites.Show(); // É necessário?


        // Chamo assim o procedimento armazenado
        General2.RefreshCartaoByYear(dataBaseName);

        // Findar a barra de progresso

        if (General2.DsRefreshCartaoByYear.Tables[0].Rows.Count > 0)
        {
            timeRefresh = General2.RefreshCartaoByYear.Tables[0].Rows[0]["TimeRefresh"].ToString();
            deletedRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["DeletedRec"].ToString();
            newRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["NewRec"].ToString();
            updatedRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["UpdatedRec"].ToString();
            errorMessage = General2.RefreshCartaoByYear.Tables[0].Rows[0]["ErrorMessage"].ToString();

            if (errorMessage.Length > 0)
            {
                resultText = "Sem resultado! \n" +
                             "Erro: " + errorMessage;
            }
            else
            {
                resultText = "Frissítés eredmény: \n" + 
                             "Időpont: " + timeRefresh + ", Könyvelési év: " + konyvalesiEv + "\n" +
                             "Törölt tételek száma: " + deletedRec + ", Új teételek száma: " + newRec + ", Módosult tételek száma: " + updatedRec;
            }

            MessageBox.Show(resultText);

            AktualiyarDataGridView();

            dgvCartao.Rows
                      OfType<DataGridViewRow>()
                      .Where(x => x.Cells["ID"].Value.ToString() == _IDSave)
                      .ToArray<DataGridViewRow>()[0]
                       .Selected = true;
        }
    }
}


namespace Total_accounts
{
  class General2
  {
    public static void RefreshCartaoByYear( string _Database)
    {
        SqlCommand commSQLCommand = new SqlCommand();
        SqlDataAdapter daSqlDataAdapter = new SqlDataAdapter();
        SqlCommandBuilder cbSQLCommandBuilder = new SqlCommandBuilder();
        SqlConnection connSQLServer1 = new SqlConnection();
        SqlDataReader dataSQLDataReader = null;

        dsRefreshCartaoByYear = new DataSet();

        try
        {
            connSQLServer1.ConnectionString = General.STRConnection; //strConnection;
            connSQLServer1.Open();
            commSQLCommand.Connection = connSQLServer1;
            commSQLCommand.CommandType = CommandType.StoredProcedure;
            commSQLCommand.CommandText = "spRefreshCartaoByYear";

            commSQLCommand.CommandTimeout = timeOut;

            daSqlDataAdapter.SelectCommand = commSQLCommand;
            cbSQLCommandBuilder.DataAdapter = daSqlDataAdapter;

            dsRefreshCartaoByYear.Clear();
            commSQLCommand.Parameters.AddWithValue("@strpmDatabase", _Database);
            daSqlDataAdapter.Fill(dsRefreshCartaoByYear, "tableRefreshCartaoByYear");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        finally
        {
            if (connSQLServer1 != null)
            {
                connSQLServer1.Close();
            }
            if (dataSQLDataReader != null)
            {
                dataSQLDataReader.Close();
            }
        }
    }
  }
}
  • it seems that the command is running on the same thread of the form, to place a progress bar, you would have to run on another thread, or display another window with the slider

  • 1

    I tried to implement many of the examples I read, unfortunately I could not do what I want. Can you give more details? I would be very grateful. Thank you for your contribution

1 answer

0

You can use an asynchronous task to perform a long procedure. This can be done as follows:

Add a "System.Threading.Tasks.Task" return in the method that performs the long procedure so that it can be 'awaitable'/expected :

public async Task MeuProcedimentoLongo()
{
  // código...
}


So you could call the procedure elsewhere:

public async void MeuMetodo() 
{
    // criacao e inicializacao da ProgressBar
    var pb = new ProgressBar();
    pb.Style = ProgressBarStyle.Marquee;
    pb.Visible = true;

    // aguarde o metodo realizar o procedimento longo
    await MeuProcedimentoLongo();
    pb.Visible = false;
}

Or I could even call you by task delegation:

public void MeuMetodo()
{
    // criacao e inicializacao da ProgressBar

    // aguarde a tarefa ser realizada
    Task.Run(async ()=> { await MeuProcedimentoLongo(); });
}

Note also that the word reserved async is used when waiting for a task within a method!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.