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开发者_如何学C. 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!
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.
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");
}
You can loop over all the controls on your form and retrieve the values from them based on their type/name.
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
}
}
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.
精彩评论