Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Windows Controls C# » Working with ProgressBar in C#

Working with ProgressBar in C#

You need progress bars to display the progress of your application or background tasks.

Author Rank :
Page Views : 552167
Downloads : 8159
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Progrs_br1.zip | ProgressBarSampleCSharp.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


A ProgressBar control is used to represent the progress of a lengthy operation that takes time where a user has to wait for the operation to be finished.

In this article, we will see how to create a ProgressBar control in a Windows Forms application using Visual Studio 2010. We will also discuss properties and methods defined in the ProgressBar class.

Creating a ProgressBar

We can create a ProgressBar control using a Forms designer at design-time or using the ProgressBar class in code at run-time.

Design-time

To create a ProgressBar control at design-time, you simply drag and drop a ProgressBar control from Toolbox to a Form in Visual Studio. After you drag and drop a ProgressBar on a Form, the ProgressBar1 is added to the Form and looks like Figure 1.

ProgressBarImg1.jpg 

Figure 1

Run-time

Creating a ProgressBar control at run-time is merely a work of creating an instance of ProgressBar class, set its properties and adds ProgressBar class to the Form controls.

First step to create a dynamic ProgressBar is to create an instance of ProgressBar class. The following code snippet creates a ProgressBar control object.

C# Code:

ProgressBar pBar = new ProgressBar();

 

VB.NET Code:

 

Dim pBar As New ProgressBar()

 

In the next step, you may set properties of a ProgressBar control. The following code snippet sets Location, Name, Width, and Height properties of a ProgressBar.

C# Code:

pBar.Location = new System.Drawing.Point(20, 20);

pBar.Name = "progressBar1";

pBar.Width = 200;

pBar.Height = 30;

 

VB.NET Code:

 

pBar.Location = New System.Drawing.Point(20, 20)

pBar.Name = "progressBar1"

pBar.Width = 200

pBar.Height = 30

 

Once the ProgressBar control is ready with its properties, the next step is to add the ProgressBar to a Form. To do so, we need to add the ProgressBar control to the Form using Controls.Add method as following.

 

C# Code:

Controls.Add(pBar);

 

VB.NET Code:

 

Controls.Add(pBar)

Setting ProgressBar Properties

After you place a ProgressBar control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

ProgressBarImg2.jpg
Figure 2

Name

Name property represents a unique name of a ProgressBar control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ProgressBar control.

C# Code:

PBar.Name = "ProgresBar1";

 

VB.NET Code:

 

PBar.Name = "ProgresBar1"

Positioning a ProgressBar

We can use the Location property to position a control. We can also dock a control using the Dock property.

Note: A ProgressBar can only be positioned horizontally.

The Dock property is used to set the position of a ProgressBar. It is of type DockStyle that can have values Top, Bottom, Left, Right, and Fill. The following code snippet sets Location, Width, and Height properties of a ProgressBar control.

C# Code:

pBar.Dock = DockStyle.Bottom;

 

VB.NET Code:

 

PBar.Dock = DockStyle.Bottom

Minimum, Maximum, and Value

The Minimum and Maximum properties define the range of a ProgressBar. The Value property represents the current value of a ProgressBar. The current value of the ProgressBar from the minimum value is colored green shows the progress of a control. We can also use the Value property to show the progress of an operation.

C# Code:

pBar.Minimum = 0;

pBar.Maximum = 100;

pBar.Value = 70;

 

VB.NET Code:

 

PBar.Minimum = 0

PBar.Maximum = 100

PBar.Value = 70

 

A ProgressBar with a value looks like Figure 3.

 

ProgressBarImg3.jpg
Figure 3

RightToLeftLayout and MarqueeAnimationSpeed

The default progress of a ProgressBar is from left to right. But the ProgressBar control can also show the progress from right to left by setting RightToLeftLayout to true. The MarqueeAnimationSpeed property represents the time period, in milliseconds, that it takes the progress block to scroll across the progress bar.

Summary

In this article, we discussed discuss how to create menus using the ProgressBar control. First we discussed how to create menus at design-time and run-time. After that we saw, how to set menus properties and click event handlers.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Alan C Balkany on Jun 17, 2009
The article is short and simple, which is good, but it's TOO short and simple.  A working example that can be copied and pasted would make this article infinitely more useful.  Also compiling the code before posting it would allow the typos to be identified and corrected.
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Some Clarification by Mahadevakumar On May 3, 2007
Reply | Email | Modify 
Re: Some Clarification by Sreejith On March 16, 2009
its the code for progress bar thank you
Reply | Email | Modify 
progress bar with oracleconnection by aissam On July 26, 2007
hello i have problem to execute progress bar with oracel connection this is my code: Timer1.Start() Try Dim cn As New OracleConnection("Password=password;User ID=dph;Data Source=creative;Persist Security Info=True") cn.Open() cn.Close() Catch ex As Exception MsgBox("sdsqdqdq") End Try Timer1.Stop() think you
Reply | Email | Modify 
Working with Progress Bar by Surendra On January 28, 2009
Hi, This is Surendra Gurjar, I learn from the this tutorial and it is very useful.
Reply | Email | Modify 
error in progressbar.increment(i) check the code by Sreejith On March 16, 2009
using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
using System.Drawing;
using System.Linq;
 using System.Text;
using System.Windows.Forms;
 using System.Threading;
 namespace WindowsFormsApplication1
 {
 public partial class Form1 : Form { Thread st; public Form1() { InitializeComponent();
 }
private void Form1_Load(object sender, EventArgs e)
 {
st = new Thread(new ThreadStart(load));
 }
public void load()
 {
for (int i=0;i<=100;i=i+1)
 {
progressBar1.Increment(i);
statusStrip1.Text = progressBar1.Value.ToString() + "%omplete"; Thread.Sleep(500); }
}
private void progressBar1_Click(object sender, EventArgs e)
 {
}
 private void button1_Click(object sender, EventArgs e)
 {
st.Start();
 }
private void button2_Click(object sender, EventArgs e)
 {
 if (st.IsAlive)
{
 st.Abort();
 } } } }
Reply | Email | Modify 
Re: error in progressbar.increment(i) check the code by Bechir On March 18, 2009

Ok my freind you have made a serious mistake, you have made an illegal cross threaded manipulation, I explain, you have invoked the both progressbar1 and statusbar1 outside the thread where they have been created. As a solution to this problem you have to create a delegate that points to a method that perform the controls' modifications (progress for the progress bar and text change for the statusbar) and then invoke this delegate inside the thread method like this

 public Form1()
        {
            InitializeComponent();
           
        }
        //The thread
        Thread st;
        //The delegate instance
        Progress p;
        //The delegate class
        public delegate void Progress();

        private void Form1_Load(object sender, EventArgs e)
        {
            st = new Thread(new ThreadStart(load));
            p = new Progress(Perform);

        }
        //The method that will be pointed by  the delegate instance
        public void Perform()
        {
            for (int i = 0; i <= 100; i = i + 1)
            {
                progressBar1.Increment(i);
                statusStrip1.Text = progressBar1.Value.ToString() + "%omplete"; Thread.Sleep(10);
            }
            DialogResult dlg = MessageBox.Show("Do you want to close this window", "Do you want to exit this window", MessageBoxButtons.OKCancel);
            if (dlg == DialogResult.OK) Application.Exit();
          
        }
        //The thread method
        public void load()
        {
            Form1 form = this;
            form.Invoke(p);
        }
        //The button that triggers the thread
        private void button1_Click(object sender, EventArgs e)
        {
           st.Start();
           //To avoid thread multi invocation
           button1.Enabled = false;
        }
Reply | Email | Modify 
Re: Re: error in progressbar stop code by Sreejith On April 19, 2009
Thanx pal for making it currect ,well the progressbar is working fine but the stop button is not working .I know calling abort in thread is not fair ,,can u make that stop button currect ...
Reply | Email | Modify 
working with Progress bar in c# by Muhammad Rehan On March 21, 2009
Hi I m Rehan Qureshi.........This code solved my big problems about the working of progress bar without experience........thank for that
Reply | Email | Modify 
Re: working with Progress bar in c# by mark On December 24, 2009
Progress bar is simple, is it for web browser or just basic load of an event?
Reply | Email | Modify 
thank by arun On January 1, 2010
Thank u
Reply | Email | Modify 
C# Progress Bar by Ali On February 11, 2010

To understand how the C# Progress Bar works, read this post.

Reply | Email | Modify 
Download progress bar by Manoj On May 7, 2010
Hi..............
Thank you Mahesh Chand Sir for download files progrs_br1.zip.

From
Manoj kumar
Dehradun (UA)
+91-9458106336

Reply | Email | Modify 
well by jchbjsnc On May 19, 2010
well
Reply | Email | Modify 
Help me in Progress bar by Sharique On September 8, 2010
For the Below Code, I want to add a progress bar: while data inserted into the another table. It takes 1 to 2 mins, for this I want to show the progress bar till the data completely not inserted


private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(@"Data Source=HAIDER-IT;Initial Catalog=csoft;Integrated Security=True");
                conn.Open();
                SqlCommand cmd = new SqlCommand("Search",conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 1800;
                cmd.Parameters.Add("@P_prd", SqlDbType.VarChar, 50).Value = "11";
                cmd.Parameters.Add("@P_rep", SqlDbType.VarChar, 50).Value = "31";
                cmd.Parameters.Add("@P_yy", SqlDbType.VarChar, 50).Value = "2008";
                cmd.Parameters.Add("@P_mm", SqlDbType.VarChar, 50).Value = "04";
                cmd.Parameters.Add("@P_HS", SqlDbType.VarChar, 50).Value = "1";
                int I = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
          
              MessageBox.Show("Data Inserted");
           
        }

Reply | Email | Modify 
http://www.csharphelp.com/wp-content/themes/twentyten/images/headers/path.jpg by Nasir On April 28, 2011
http://www.csharphelp.com/wp-content/themes/twentyten/images/headers/path.jpg
Reply | Email | Modify 
WPF Progress Dialog by Jürgen On June 18, 2011
Great article! Here you find another nice article about how to implement a WPF progress dialog: http://www.parago.de/2011/04/how-to-implement-a-modern-progress-dialog-for-wpf-applications/
Reply | Email | Modify 
Re: WPF Progress Dialog by Puma On July 6, 2011
Hallo, ich versuche gerade eine ProgressBar in einer eigenen WinForm zu erstellen. Hier mein Ansatz: C#-Code: public partial class RIM_ProgressBar : Form { Thread _thread; int _val; public int Value { set {this._val=value; } get { return this._val; } } public RIM_ProgressBar(int min, int max, int actual) { InitializeComponent(); progressBar1.Minimum = min; progressBar1.Maximum = max; progressBar1.Value = actual; _val = actual; } private void RIM_ProgressBar_Load(object sender, EventArgs e) { _thread = new Thread(new ThreadStart(load)); _thread.Start(); } public void load() { progressBar1.Value = _val; statusStrip1.Text = progressBar1.Value.ToString() + "%omplete"; // Thread.Sleep(10); } public void changeValue(int val) { this._val = val; } } So ruf ich das auf: C#-Code: RIM_ProgressBar rProgBar = new RIM_ProgressBar(0, 100, 0); rProgBar.Show(); for (int i = 0; i < 100; i++) { rProgBar.Value = i; Thread.Sleep(10); } Es funktioniert nicht...
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.