Gerharddc
Gerharddc

Reputation: 4089

Use variable as part of textbox name in C#

I am developing a program wth 30 text boxes and 30 check boxes next to them. I want people to check names and then press the send button. The program then saves the names in a txt file with a true or false statement next to them, it then uploads the file to a ftp server for me analize. The problem I am facing is that I don't want to write code for every text and check box to load and save it's value on the txt file. If I name the text boxes something like tbox1;tbox2;tbox3 etc. How would use a loop to say write the value of tbox i + ; + cbox i on line i of thing.txt or vice versa? Please any help would be grately apreciated because this will save me a lot of unnesacery code writing!

Upvotes: 2

Views: 11551

Answers (5)

Stecya
Stecya

Reputation: 23276

        for (int i = 0; i <= count; i++)
        {
            TextBox textbox = (TextBox)Controls.Find(string.Format("tbox{0}", i),false).FirstOrDefault();
            CheckBox checkbox = (CheckBox)Controls.Find(string.Format("cbox{0}", i),false).FirstOrDefault();

            string s = textbox.Text + (checkbox.Checked ? "true" : "false");
        }

Upvotes: 2

Richard Cox
Richard Cox

Reputation: 501

Assuming this is ASP.NET, you could use something like this:

StringBuilder sb = new StringBuilder();
for(int i = 1; i < 30; i++){
    TextBox tb = FindControl("TextBox" + i);
    Checkbox cb = FindControl("CheckBox" + i);
    sb.AppendFormat("TextBox{0}={1}; {2}", i, tb.Text, cb.Checked);
}
string result = sb.ToString();
// Now write 'result' to your text file.

Upvotes: 0

Morten
Morten

Reputation: 3854

Loop through controls in your form/control and investigate name:

        foreach (Control control in f.Controls)
        {
            if (control is TextBox)
            {
               //Investigate and do your thing
            }
        }

Upvotes: 0

SLaks
SLaks

Reputation: 888303

You should create a List<TextBox>, and populate it with your textboxes in the constructor.

You can then loop through the list and process the textboxes.

Upvotes: 4

Jens
Jens

Reputation: 3299

You can loop over all the controls on your form and retrieve the values from them based on their type/name.

Upvotes: 1

Related Questions