I have this code, which seems too repetitive, so I wanted to use a loop to make it better:
//Converts a text in a integer using a custom method based on int.TryParse
int a1 = determinantes.aEntero(a1Box.Text);
int a2 = determinantes.aEntero(a2Box.Text);
int a3 = determinantes.aEntero(a3Box.Text);
int b1 = determinantes.aEntero(b1Box.Text);
int b2 = determinantes.aEntero(b2Box.Text);
int b3 = determinantes.aEntero(b3Box.Text);
int c1 = determinantes.aEntero(c1Box.Text);
int c2 = determinantes.aEntero(c2Box.Text);
int c3 = determinantes.aEntero(c3Box.Text);
//I pass those new ints to a method to do something with them
resultado.Text = determinantes.detGrado3(a1, a2, a3, b1, b2, b3, c1, c2, c3).ToString();
The first part could be done using arrays a[1], a[2]... but I'd need to change the names of the variables to make the start with the same letter.
The second part I have no clue of how it can be done. I though doing something like
a[counter] = determinantes.aEntero(a[counter]Box.Text);
But obviously that won't work. So, do you have any ideas how I can use a loop in that code?
Thanks
[UPDATE]
I'm having the same problem in the code of a "clear" button, too:
a1Box.Text = "";
a2Box.Text = "";
a3Box.Text = "";
b1Box.Text = "";
b2Box.Text = "";
b3Box.Text = "";
c1Box.Text = "";
c2Box.Text = "";
c3Box.Text = "";
d1Box.Text = "And so on till the infinite!";
[UPDATE] Finally I've come to this. I think it's right now. Thank you all guys!
TextBox[] boxes = new TextBox[] { a1Box, a2Box, a3Box, b1Box, b2Box, b3Box,
c1Box, c2Box, c3Box };
int[] enteros = new int[boxes.Length];
for (int f = 0; f < boxes.Length; f++) {
enteros[f] = determinantes.aEntero(boxes[f].Text);
}
resultado.Text = determinantes.detGrado3Arr(enteros).ToString();
I'd say throw the text values into an array, loop through that, and assign to a second array, then tell your consuming function to take it as a parameter.
Pseudo:
string[] boxes = new string[] {a1box.Text, a2box.Text, ...etc etc ...lastbox.Text};
int[] results = new int[boxes.length];
for(i = 0; i < results.Count; i++)
{
results[i]= determinantes.aEntero(boxes[i]);
}
resultado.Text = determinantes.detGrado3(results)
//you should return a string
//instead of using the ToString() method if possible`
Also, there's a built in way to handle your 'clear' issue.
foreach(Control c in this.Controls)
{
if(c.GetType = typeof(TextBox))
{ ((TextBox)c).Clear(); } //or ((TextBox)c).Text = string.Empty, if you prefer
}