Search code examples
c#visual-studiofor-looptextbox

I have multiple text boxes (tbVarName1, tbVarName2, ... tbVarName[n]) and I want to increment them in a for loop to assign the text to something


I have a multiple text boxes that I want to assign their string content to a variable however I'm not sure how to increment the text boxes. They are named, tbVarName1, tbVarname2, et cetera. Below is the for loop I have, right now I just have tbVarName1 hard coded in.

I have researched some of what other people have done and have only found tips for doing it in VB.

        for(seriesIndex = 1; seriesIndex <= 4; seriesIndex++)
        {
                dataChart.Series["Variable " + seriesIndex].LegendText = tbVarName1.Text 
        }

At the end of this I would like the the legends to be updated to what's in the text boxes


Solution

  • There are various ways to do this, one way is to add the controls into an array, for example:

    var controls = new [] { tbVarName1, tbVarName2, tbVarName3 };
    

    And now you can access them by index:

    for(seriesIndex = 1; seriesIndex <= 4; seriesIndex++)
    {
        dataChart.Series["Variable " + seriesIndex].LegendText = controls[seriesIndex - 1].Text;
        //                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^
        //                                                       Like this
        //                                                       Note: arrays start at zero
    }