How can I put a progress bar inside this code:
(I was trying to use PerformStep method for counting rows in data table, and put this code, but no luck: http://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.performstep.aspx)

private void DocumentInserting ()
        {
            string MyFilePath = System.IO.Path.GetTempPath() + @"MyNotices\";
            string MyFolderPath = MyFilePath + @"Notices.xml";
            DataSet ds = new DataSet();
            ds.ReadXml(MyFolderPath, XmlReadMode.ReadSchema);
            progressBar1.Visible = true;
            label1.Visible = true;
            label1.Text = progressBar1.Value.ToString() + " % finished";
            progressBar1.Minimum = 1;
            //I have started, but do not know how to do a loop for counting the rows in data table!
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                
                string insertion = "INSERT INTO NoticeTable VALUES(@IDNotice, @Number, @Name)";
                SqlCommand cmd1 = new SqlCommand(ObvestiloVnos, povezava);                
                cmd1.Parameters.Add("@IDNotice", SqlDbType.Int);
                cmd1.Parameters.Add("@Number ", SqlDbType.VarChar, 50);
                cmd1.Parameters.Add("@Name", SqlDbType.VarChar, 50);

                cmd1.Parameters["@IDNotice"].Value = dr[0];
                cmd1.Parameters["@Number"].Value = dr[1];
                cmd1.Parameters["@Name"].Value = dr[2];
                try
                {
                    sqlConn.Open();
                    cmd1.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }                
            }
            sqlConn.Close();
            ds = null;
        }
// Set the number of rows to step through...
                progressBar1.Maximum = ds.Tables[0].Rows.Count;

                // Set the increment size...
                progressBar1.Step = 1;

then to maintain progress:

cmd1.ExecuteNonQuery();

                        // Increment progress...
                        progressBar1.PerformStep();

You should also move the sqlConn.Open(); outside of your loop, which is why I didn't include it above. There is no need to reopen the connection for every command (INSERT) you are executing.

Here is an example of how you implement the BackgroundWorker instead of trying to implement the ProgressBar independently. If you use this technique, avoid using the PerformStep() altogether (even though it is possible to do).

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Number of items to process in our loop...
            const int total = 137;

            for (int i = 0; i < total; i++)
            {
                // check cancellation flag. See documentation for multi-threading remarks!!!
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;

                    // Optional: Set a result that can be accessed in RunWorkCompleted event...
                    e.Result = "Work haulted; failure ocurred...";

                    return;
                }
                else
                {
                    // Simulate some processing time....
                    System.Threading.Thread.Sleep(50);

                    // calculate progress...
                    int pct = (int)((i + 1.0) / total * 100);

                    // verify calculation....
                    Console.WriteLine(pct);

                    // Update the progress bar...
                    worker.ReportProgress(pct);
                }
            }
            // Optional: Set a result that can be accessed in RunWorkCompleted event...
            e.Result = "Work completed; no errors encountered...";
        }

        // using ProgressPercentage...
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Set the current progress value and update the control...
            progressBar1.Value = e.ProgressPercentage;
            progressBar1.Update();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string msg;

            if (e.Cancelled == true)
            {
                // Use message we passed in 'Result'...
                if (e.Result != null)
                    msg = (string)e.Result;
                
                else
                    msg = "Canceled; Reason unknown!";
            }

            else if (e.Error != null)
                msg = ("Error: " + e.Error.Message);
            
            else
                msg = "Done!";
            

            MessageBox.Show(msg);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Cannot set these values in the worker's method because it will
            // be executing on a different thread in the background...
            progressBar1.Maximum = 100; // always use 100 because using upto 100% for progress!!!
            progressBar1.Minimum = 0; // always start at 0 because cannot be greater than 'Value' property!!!
            progressBar1.Value = 0; // initialize to zero progress...
            progressBar1.Step = 9999; // forget about this value because we are not using step for backgroundworker!!!

            // Begin processing...
            backgroundWorker1.RunWorkerAsync();
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.