Search code examples
c#winformsprogress-barwindows-forms-designer

C# Progress Bar Min value is not updating from textbox


Im trying to work with progress bar in C# WFA. My code works but i have problem with Min value of progress bar. It only works when i enter max value first not min. When i enter min value first it starts from 0 every time i dont know why. Any ideas?

    private void textBoxWartosc_TextChanged(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(textBoxWartosc.Text))
        {

        }
        else
        if ((Convert.ToInt32(textBoxWartosc.Text)) >= (Convert.ToInt32(textBoxMin.Text)) && (Convert.ToInt32(textBoxWartosc.Text)) <= (Convert.ToInt32(textBoxMax.Text)))
        {
            int i = Convert.ToInt32(textBoxWartosc.Text);
            progressBar1.Value = i;
        }
    }


    private void textBoxMax_TextChanged(object sender, EventArgs e)
    {
        int i = Convert.ToInt32(textBoxMax.Text);
        progressBar1.Maximum = i;
    }

    private void textBoxMin_TextChanged(object sender, EventArgs e)
    {
        int i = Convert.ToInt32(textBoxMin.Text);
        progressBar1.Minimum = i;
    }

Solution

  • First let's take a look at how the ProgressBar behaves. The main rule is that the minimum will always be less than or equal to the maximum. So if you change the value of maximum to something less than the minimum, you are changing the minimum too. clear?

    So, I guess this is the case here: first you change the minimum to something lets say 120, you'll have:

    minumum = 120 , maximum = 120    // maximum also changes from 100 to 120 based on the rule
    

    then you try to input the maximum amount to let's say 180, but the TextChanged event gets called three times. First, as soon as you insert the "1", so you will have:

    minimum = 1 , maximum = 1    // minimum also changes because 1 is less than 100
    

    Second, when you enter "8", now you will have:

    minimum = 1 , maximum = 18   // now minimum stays 1
    

    and then when you enter the final "0" and the final situation will be:

    minimum = 1 , maximum = 180
    

    There are lot's of ways to solve this, but I suggest

    1: you use the Leave event instead of TextChanged

    or 2: put a Save button there and change alter values only when the button is pressed.