Home > Back-end >  C# : bool array is not updating during execution
C# : bool array is not updating during execution

Time:01-09

i have this sample code which basically reads some string data from csv file and updates in textboxes and some variables.

The csv file is of the format 10,0,20,0,0,30,0..etc with 20 values. The idea is, if any of the value in csv file is 0, the isCashAvailable variable should be set to false and vice versa. Below is my code.

int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

public void UpdateCash()
{
        var cashCSV = File.ReadAllText("cash.csv");
        List<string> cashVal = cashCSV.Split(',').ToList();
        
        for (int i = 1; i <= 20; i  )
           {
            var control = this.Controls.Find("textBox"   i.ToString(), true).FirstOrDefault() as TextBox;
            if (cashVal[i - 1] != "0")
              {
                 isCashAvailable[i - 1] = true;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);
              }
                            
            else
              {
                 isCashAvailable[i - 1] = false;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);
                 
              }
           }
}

Now the issue is, when I try to update the value of the isCashAvailable and cash in runtime, its not updating. Whereas if am debugging it by stepping over each iteration, its updating. Can't seem to find why this is happening.

CodePudding user response:

Try this:

int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

var cashCSV = File.ReadAllText("cash.csv");
List<string> cashVal = cashCSV.Split(',').ToList();

// changing this allows you to use i 1 just once, instead of doing i-1 over and over
for (int i = 0; i < 20; i  )
   {
    // this way it will throw an error if TextBox is not found instead of
    // not throwing it here and then throwing NullReference later
    var control = this.Controls.Find("textBox"   (i 1).ToString(), true).First() as TextBox;
    
    //if-else is not needed here
    //TryParse to make sure it always works
    int.TryParse(cashVal[i], out cash[i]);
    isCashAvailable[i] = (cash[i] > 0);
    control.Text = cashVal[i];

    //it works
    Debug.Print($"{i}: isCashAvailable = {isCashAvailable[i]}, cashVal = {cashVal[i]}");
   }
  •  Tags:  
  • Related