0
votes

I am developing an application using Windows Form and C#. How can I add the Text of all textboxes on the current tabpage to a List<string> Mydata. Here is my code below:

foreach(Control c in Controls){
    if((c is TextBox) && (c.Text !="")){
         if(c.Tag.ToString() == "500"){
             StaticClass.Mydata.Items.Add(c.Text);
         }
    }
}

NB: Mydata (List) is public on a static class. I have a form with a tabcontrol which contains about 6 tabpages. The other tabpages have textboxes, too, but I want to retrieve only those in my example on tabindex 5.

Thanks.

2
Get the tabpage and call .Controls on it. Instead of this.Controls. - Derek
You can give a name to the textbox and then you can find it very easily stackoverflow.com/questions/3898588/…. Because the chances are the textbox may not be the control of tabpage i.e. may control of any other control which is inside the tabpage. - lkdhruw
Texboxes has they names and the thing which is common to them is tag number. - Joel Mayer Mukanya
All textboxes has it own names - Joel Mayer Mukanya
Ikdhruw: The above question it not the same with the one on the link. I think I can try dereck answer and see if I can solve my logic - Joel Mayer Mukanya

2 Answers

1
votes

If I understand you correctly you need to get the text from all TextBoxes within a TabPage, but only if the Tag property is equal to the string "500".

Your code is basically right, but I've modified it slightly (removed some redundant parenthesis etc.). I'm assuming that your TabPage is named tabPage1, indexOfTabPage is the index of the TabPage and the results are placed in a local List.

You can just add the strings to a static list instead if you like.

int indexOfTabPage = 5;
List<string> myData = new List<string>();

foreach(Control c in this.tabControl1.TabPages[indexOfTabPage].Controls)
{
   if(c is TextBox && !string.IsNullOrEmpty(c.Text) && c.Tag != null && c.Tag.ToString() == "500")
   {
      myData.Add(c.Text);
   }
}
0
votes
        private void GetTextBoxValueFromCurrentTabPage()
        {
            List<string> lstTextBoxData = new List<string>();
            foreach (var textBox in tabControl1.TabPages[tabControl1.SelectedIndex].Controls.OfType<TextBox>())
            {
                lstTextBoxData.Add(textBox.Text.Trim());
            }
        }

        private void GetTextBoxValueFromAllTabPages()
        {
            List<string> lstTextBoxData = new List<string>();
            foreach (TabPage tabPage in tabControl1.TabPages)
            {
                foreach (var textBox in tabPage.Controls.OfType<TextBox>())
                {
                    lstTextBoxData.Add(textBox.Text.Trim());
                }
            }
        }