Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

Can someone please clarify to me how background worker actually works. I would like to do a simple login form that will show login progress to the user after they click loggin since normally it will take long to read login details therefore I would like to update the user instead of letting the ui hang.

I have tried the code below but I am not sure how or where do I save the result so that I can display to the user if login is successfull or not.


Any assistance will be much appreciated.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
namespace LoginDemo
{
    public partial class Form1 : Form
    {

    
        public Form1()
        {
            InitializeComponent();
        }
        //Login will be cancelled
        private void btncancel_Click(object sender, EventArgs e)
        {
            if(backgroundWorker1.WorkerSupportsCancellation == true){
                backgroundWorker1.CancelAsync();
                btnlogin.Enabled = true;
                btncancel.Enabled = false;           
            }
        }
        //Login will be processed
        private void btnlogin_Click(object sender, EventArgs e)
        {
        
            testobj.username = txtid.Text.Trim().ToString();
            if (txtid.Text == string.Empty)
            {
                MessageBox.Show("Please enter username", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtid.Focus();
            }
            else
            {
                lblMessage.Visible = true;
                progressBar1.Visible = true;

                testobj.ReadData();
                backgroundWorker1.RunWorkerAsync();
                btnlogin.Enabled = false;
                btncancel.Enabled = true;
              /*  if (chckrbm.Checked == true)
                {
                    IMACBOX.Properties.Settings.Default.loginUsername = username;
                    IMACBOX.Properties.Settings.Default.Save();
                }*/

             //  ReadData(connectionString);
            }
            
            
            
            
          

        }
        // Will handle the heavy work
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            int dataload = 0;
            for (dataload = 0; dataload <= 100; dataload++)
            {
                if (backgroundWorker1.CancellationPending == true)
                {
                   
                    //user clicked cancel button
                    e.Cancel = true;
                    backgroundWorker1.ReportProgress(0);
                   break;
                }
                else {
                    //do the heavywork
                   // ReadDatas();
                  //  dataload += 1;
                   // testobj.ReadData();
                    backgroundWorker1.ReportProgress(dataload);//Report progress
                }
            }
            e.Result = dataload;
        }
        // Will update progressbar on heavy work progress
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Updater progress bar

           
            progressBar1.Value = e.ProgressPercentage;
            lblMessage.Text = "Loading..." + e.ProgressPercentage.ToString() + " %";
            
        }
        // Will update when progress is completed
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Check progress before displaying message

            if (e.Cancelled == true)
            {
                MessageBox.Show("Operation Cancelled ", "Cancelled ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                progressBar1.Value = 0; // Reset progressbar value if user cancelled
                lblMessage.Text = "";//clear the label
                progressBar1.Visible = false;
            }
            else if (e.Error != null)
            {

               // String somethingwrong = e.Result.ToString();
                MessageBox.Show(e.Error + "Error found " + e.Error.Message , "Error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                progressBar1.Value = 0; // Reset progressbar value if user cancelled
                lblMessage.Text = "";//clear the label

            }
            else {
                MessageBox.Show("Progress done " + e.Result.ToString() + " ","Done ",MessageBoxButtons.OK,MessageBoxIcon.Information);
                progressBar1.Value = 0; // Reset progressbar value if user cancelled
                lblMessage.Text = "";//clear the label
            }
        }
        //Method for doing the heavy work
        private void ReadDatas() {
            try {

                Thread.Sleep(100);


            }catch(Exception e){

                MessageBox.Show("Login Result ", e.Message , MessageBoxButtons.OK,MessageBoxIcon.Information);
                progressBar1.Value = 0; // Reset progressbar value if user cancelled
                lblMessage.Text = "";//clear the label
            }
        }

      

        private void Form1_Load(object sender, EventArgs e)
        {
          //  username = txtid.Text.Trim();
         //   status = lblMessage.Text.ToString();
          //  bar = progressBar1.Value;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
using System.Data;
namespace LoginDemo
{
    class testobj
    {

        public static String username, lastname, firstname, status, lblMessage;
        public static int progressBar1Value = 0;
        public static string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\IMAC\APP\IMACDB\FormDB2.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'";
        // public string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\132.186.144.184\d$\FormDB4.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'";
        //   public string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\132.186.144.239\d$\IMAC\APP\IMACDB\FormDB2.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'";
        public static OleDbConnection cnn;
        public static OleDbCommand cmd;
        public static OleDbDataAdapter da;
        public static OleDbDataReader dr;
        public DataSet dstResults = new DataSet();
        public DataView myView;
        public DataTable dtable;
        public DataColumn c;
    
     public static  void ReadData()
        {

            try
            {
             
                string queryString = "SELECT Employee_ID,LastName,FirstName FROM [Entries$] WHERE Employee_ID ='" + username.Trim().ToString() + "'";
                dr = null;
                cnn = new OleDbConnection(connectionString);
                cmd = new OleDbCommand(queryString, cnn);
                cnn.Open();
                dr = cmd.ExecuteReader();



            
                
                if (dr.Read() == true)
                {
              
                    Thread.Sleep(100);
                    // MessageBox.Show("Progress bar");
                    firstname = dr[1].ToString();
                    lastname = dr[2].ToString();
                    MessageBox.Show("Login successfull"); 
            
                }
                else
                {
                    MessageBox.Show("Username Invalid", "Error Message");

                }
                // Always call Close when done reading.
                dr.Close();
            }
            //  }
            catch (Exception e)
            {
                MessageBox.Show("Error " + e.Message, "Error");
            }
         

       }
    }
}
Posted
Comments
Richard Deeming 8-May-17 14:10pm    
"I am not sure how or where do I save the result"

In e.Result - as your code is already doing.

What is the problem?
Member 7763261 9-May-17 1:53am    
Hi Richard,

Thank you for your response. Please bare with me as I am new to thing backgroundworker control. It seems like my progressbar only executes after the time consuming code of which I would like to update the progress bar to let the user know that the data is loading. how do I retrieve the result from that e object?
Richard Deeming 9-May-17 6:57am    
Based on the code you've posted, all of the work is commented out, so it's going to be impossible to see whether the progress bar updates while the worker is running.
Member 7763261 9-May-17 8:13am    
I have uncommented testobj.ReadData() and also used lblMessage from my testobj class to display messages but the progressbar runs only after. now do I have to declare use progressBar1Value from my testobj class to hold progress as well. because from what I have read I cannot access ui controls from dowork
Richard Deeming 9-May-17 8:34am    
Have you double-checked that the WorkerReportsProgress property is set to true?

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