Answered How to colour a textbox which contain the maximum value of a two-dimensional array?

houp_jd

New member
Joined
Nov 20, 2019
Messages
2
Programming Experience
Beginner
I have a two-dimensional array of random integers that are in an array of textboxes. I found the maximum and brought it to Label1. Everything works. But I still need to colour the textbox in which this maximum is located. I had versions, but unsuccessful. Please help, who knows where the error is?
C#:
int max = Convert.ToInt32(t[0, 0].Text);

for (i = 0; i < x; i++)
  {
   for (j = 0; j < y; j++)
    {
      if (Convert.ToInt32(t[i, j].Text) > max)
       {
          max = Convert.ToInt32(t[i, j].Text);
          t[i, j].BackColor = Color.Red;
          label1.Text = "" + max;
       }
     }
   }
 
Last edited by a moderator:
You should not be making any changes to the UI inside the loop. As it is, you could end up colouring every TextBox, if the values were in ascending order. You should declare another variable for the TextBox containing the max value and then just update the two variables inside the loop. Once the loops are done, colour the TextBox in the one variable and display the other variable in the Label.

Also, don't do this:
label1.Text = "" + max;
That's dodgy. If you want to convert a number to a String then do that:
label1.Text = max.ToString();
 
You should not be making any changes to the UI inside the loop. As it is, you could end up colouring every TextBox, if the values were in ascending order. You should declare another variable for the TextBox containing the max value and then just update the two variables inside the loop. Once the loops are done, colour the TextBox in the one variable and display the other variable in the Label.

Also, don't do this:
label1.Text = "" + max;
That's dodgy. If you want to convert a number to a String then do that:
label1.Text = max.ToString();
Thank you so much. I corrected the code a bit and now progarm works. Thanks for tips!
 
Back
Top Bottom