65.9K
CodeProject is changing. Read more.
Home

Access Values of ProgressBar Created a Runtime

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Oct 23, 2014

CPOL
viewsIcon

11670

Access values of ProgressBar created at runtime

Introduction

This tip applies to anyone that needs to create .NET ProgressBar controls at runtime and access its value.

Background

A regular knowledge of C#/VB.NET is useful to understand this tip.

Using the Code

During the build of a project, I had to put 255 ProgressBar controls in a form. The best way to perform it is during the code runtime, utilizing the following steps:

//
// Add ProgressBar
//
 Dim PosX As Integer = 10
 Dim PosY As Integer = 10


For X as integer = 0 To 255

   Dim MyBar As ProgressBar = New ProgressBar
   With MyBar
	.Name = "MyBar" & X.ToString
	.Location = New System.Drawing.Point(PosX + 90, PosY)
	.Width = 180
	.Height = 13
	.Value = 1
	.Maximum = 100
	.BackColor = Color.Black
	.ForeColor = Color.DarkGoldenrod

   End With
   Me.Controls.Add(MyBar)

   PosY += 13

Next

...

The problem had appeared when I tried to access their values. Visual Studio does NOT allow us to set the ProgressBar value directly if it was created at runtime:

//
// Set values of MyBars
//

 For xx = 0 To 255

	dim EachValue as integer = (Counter(xx) * 100) / GreaterNumber
	Me.Controls("MyBar" & xx.ToString).value = EachValue

 Next

...

If you try the code above, Visual Studio won't display the value property. In fact, VS won't display any ProgressBar property!

So, I would have two choices: create 256 ProgressBar controls in design-mode OR discover a way to access the controls values programmatically. I had discovered a way and I'll share it now with all CodeProject users: you just have to access it indirectly through a new control. See the sample:

//
// Set values of MyBars
//

 For xx = 0 To 255
	dim EachValue as integer = (Counter(xx) * 100) / GreaterNumber
	Dim TmpObj As ProgressBar = Me.Controls("MyBar" & xx.ToString)
	TmpObj.Value = EachValue
 Next

...

Pretty simple, but I lost a lot of time searching for that solution on the internet. I hope it can be useful to you.

Access Values of ProgressBar Created a Runtime - CodeProject