I have 4 textboxes that I need to run the same function on. Instead of typing out the function 4 times I want to be able to run a loop that does it for me. I'm not sure how to go about doing this. The text boxes are all named as such txtblah1 txtblah2 txtblah3 txtblah4. The function takes in txtblah1.Text. How would I loop through changing the 1 to a 2 and so on?
I would think in the example above a for each loop could be used but the double vars should be and array rather than 4 different vars. You could also do this with a control array and probably a couple of other ways as well.
That said if it is really only 4 items as simple as in the OP I would not bother as the code there would likely be faster anyway and apparently has already been written.
A little late where I am and probably not the best answer due to my inexperience but how about something like this?
// Class level list containing Text boxes for calculating
List<TextBox> txtList = new List<TextBox>(10);
// Add text box to list. Only have to be added in once
private void btnCalculate_Click(object sender, EventArgs e))
// Run a foreach loop
foreach (TextBox t in txtList)
t.Text = Calculate(t.Text, 0.45).ToString();
private double Calculate(string firstVal, double secondVal)
// Do some calculation
double calcTotal = double.Parse(firstVal) * secondVal;
// Return double
Don't know the efficiency of doing something like that though as it seems like it would get confusing fast.
The only advantage to the code I can see would be the ability to use a foreach loop and change the calculate function to something else without having to write out too much code.