Click here to Skip to main content
15,921,660 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I'm trying to link a progressbar with datagridview when a button is clicked.The problem is that the datagridview is fetched before the progressbar starts to run.

How can i edit my code so that the progressbar show me the progress while the datagridview is fetch / filled.
I'm using a Backgroundworker.

C#
/* Backgroundworker for the progressBar*/
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                int sum = 0;
                //for (int i = 1; i <= 100; i++)
                    for (int i = 0; i < datagridview1.Rows.Count - 1; i++)
                {
                    Thread.Sleep(10);
                    sum = sum + i;
                    backgroundWorker1.ReportProgress(i);
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true;
                        backgroundWorker1.ReportProgress(0);
                        return;
                    }
                }

                e.Result = sum;
            }


The Button function:

C#
  private void btnShow_Click(object sender, EventArgs e)
    {
        progressBar1.Visible = true;

        if (cb1.SelectedItem != null && cb2.SelectedItem != null)
        {
            string C = ConfigurationManager.ConnectionStrings["D"].ConnectionString;
            SqlConnection con = new SqlConnection(C);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = ("[dbo].[spData]");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Table_Name", cb1.SelectedValue.ToString());
            cmd.Parameters.AddWithValue("@Table_Name2", cb2.SelectedValue.ToString());
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);



if (cb1.SelectedValue.ToString() != null && cb2.SelectedValue.ToString() != null)
            {
                try
                {

                    con.Open();
                    dt = new System.Data.DataTable();
                    adapter.Fill(dt);
                    //datagridview1.AutoGenerateColumns = true;
                    datagridview1.DataSource = dt;
                    lbtblCount.Text = cb1.Text + " Anzahl : " +  datagridview1.Rows.Count.ToString();

                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                }

            }

        }
        else
        {
            MessageBox.Show("Safety check");
        }

        // Check if the backgroundworker is already busy running the asynchronous operation
        if (!backgroundWorker1.IsBusy)
        {
            //This method will start the execution asynchronously in the background
            backgroundWorker1.RunWorkerAsync();
        }
        else
        {
            label7.Text = " Busy processing, please wait";
        }
    }


Would be glad for an help
Posted
Updated 1-Feb-15 23:57pm
v2

 
Share this answer
 
Comments
mikybrain1 2-Feb-15 8:13am    
Thanks for the link BUT my question was how can i connect it properly with my datagridview.
Hi,

Here a sample check this

C#
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        BackgroundWorker bw;
        bool isGetDataFromDb = false;
        int progressCount = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            dataGridView1.AutoGenerateColumns = false;
            this.progressBar1.Value = 0;
            bw = new BackgroundWorker();
            bw.DoWork += (s, se) => 
            {
                se.Result = FillDatagRide();
                isGetDataFromDb = true;
            };
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.RunWorkerAsync();

            //just to show progress bar till data get from db.
            for (int i = 1; i < 50; i++)
            {Thread.Sleep(50);
                
                if (isGetDataFromDb)
                {
                    break;
                }
                bw.ReportProgress(++progressCount);
            }

        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ArrayList result = e.Result as ArrayList;
            foreach (var item in result)
            {
                Thread.Sleep(100);
                this.progressBar1.Value = ++progressCount;
                Invoke((MethodInvoker)(() => dataGridView1.Rows.Add(item)));
            }

            this.progressBar1.Value=100;
        }

        private ArrayList FillDatagRide()
        {
            //Code Get data from db
            Thread.Sleep(1000);
            return new ArrayList();//contain data from db 
        }
    }
 
Share this answer
 
v3
Comments
mikybrain1 4-Feb-15 4:22am    
Hi Varun,
why this line?: Invoke((MethodInvoker)(() => dataGridView1.Rows.Add("item " + i)));

I don't wanna add an item to the dgv. I'm having an error: trying to add an iten

Thnx
Varun_Kumar 4-Feb-15 4:31am    
Invoke((MethodInvoker)(() => dataGridView1.Rows.Add(item))); this is for calling element in UI thread.


either you can try by
dataGridView1.Rows.Add(item)));
mikybrain1 4-Feb-15 5:30am    
Thnx for ur help but it seems i'm a liitle bit naive and new to c# and can't integerate ur solution in my question.
But thanx thoug!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900