Amazing User
Amazing User

Reputation: 3563

How to get access to the progressBar?

In my program on the WindowsForms I have a MainForm, which contains ProgressBar. In the ChildForm I want to change it's value, but I'm getting an error:

"int" does not contain a definition for "Value". Unable to find an extension method "Value", taking first argument of type "int" (missing a using directive or an assembly reference?)

Main Form:

public int ProgressBar5
{
    get { return progressBar5.Value; }
    set { progressBar5.Value = value; }
}

Child Form:

static MainForm mainForm = new MainForm();

private void button1_Click(object sender, EventArgs e)
{         
    mainForm.ProgressBar5.Value++; // Error
}

Edit1: In the main form the value of the progressBar5 is always equals 1. What can be reason of it? I thought, that static can fix it.

Main Form:

private void button9_Click(object sender, EventArgs e)
{
    Child child = new Child();
    child.ShowDialog();
    MessageBox.Show(progressBar5.Value.ToString()); // All time Value = 1
}

Upvotes: 0

Views: 343

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61339

The problem is that you have two variables with similar names, causing quite a bit of confusion. When you try and access the ProgressBar5 variable you are actually getting the int property you declared in the first snippet.

Since int does not have a Value property, you get the compile time error. Change your code to:

static MainForm mainForm = new MainForm();

private void button1_Click(object sender, EventArgs e)
{         
    mainForm.ProgressBar5++; // Fixed!
}

Upvotes: 1

Servy
Servy

Reputation: 203802

Your ProgressBar5 property already takes care of accessing the Value property of the progress bar. It doesn't return the progress bar, but rather the current progress. This means that the caller doesn't need to access the Value property of the result (since there is none).

Just write:

mainForm.ProgressBar5++;

Of course, for clarity's sake, it would probably be better to call such a property CurrentProgress rather than ProgressBar because it doesn't return a progress bar, it returns (or sets) the current progress.

Of course, better still would be for the child for to have no knowledge of the main form at all. Rather than passing in the main form itself the child form can accept an IProgress instance. It can then report progress to whomever is creating this form, whether that be your main form, or anything else. The main form is then responsible for doing whatever it wants when progress is reported, which it can define in either an event handler or a delegate passed into the Progress constructor.

Upvotes: 3

Related Questions