dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Thread: Looping through textboxes in C#

  1. #1
    Join Date
    May 2016
    Posts
    10

    Looping through textboxes in C#

    High i did run a search in the forum so not to be redundant.
    i have about 10 textboxes to loop through.and i don't want to use the same function again and again so here is mycode below,it would appreciated if
    somebody help me with it
    " private void button1_Click(object sender, EventArgs e)
    {
    int values = Convert.ToInt32(textBox1.Text);
    if (values % 2 == 0)
    {
    textBox1.BackColor=Color.Green;
    }
    "
    My regards

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Looping through textboxes in C#

    Add a private field of type List<TextBox>, e.g.:
    private List<TextBox> textboxes = new List<TextBox>();
    Then fill the list in the constructor or in the Load event handler, so that it holds all of your textboxes.

    Then in your button click handler, you can do:

    textboxes.Where(tb => Convert.ToInt32(tb.Text) % 2 == 0).ToList()
    .ForEach(tb => tb.BackColor = Color.Green);

  3. #3
    Join Date
    May 2016
    Posts
    10

    Re: Looping through textboxes in C#

    First of all i immensely appreciate your reply,which i did apply for some reason is not working ,obviously i'm doing something wrong.All i want is to loop through 10 textboxes or so,and if the value it's odd,tb colored in a color and if it's even another color.
    My regards

  4. #4
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Looping through textboxes in C#

    Well, can you post some code, and maybe compiler error messages (if there are any), so that we can see what's wrong?

    P.S. When posting code, you can use the [code][/code] tags to preserve formatting. (If the code is not already formatted, it will not format it - it only preserves existing formatting.)

  5. #5
    Join Date
    May 2016
    Posts
    10

    Re: Looping through textboxes in C#

    HI
    Thank you for the help in advance ,the code is below,and it's not working
    Myregards
    Code:
           }
            List<int> myList = new List<int>();
        
                 TextBox[] textBoxes = { textBox1, textBox2, textBox3, textBox4 };
                 for (int i = 0; i < textBoxes.Length; i++)
                 {
    
                  private void button1_Click(object sender, EventArgs e)
            {
        
                textboxes.Where(textBox=> Convert.ToInt32(textBox.Text) % 2 == 0).ToList()
                      .ForEach(textBox => textBox.BackColor = Color.Green);
            }
        }
    }

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,173

    Re: Looping through textboxes in C#

    No need to create a separate array as the form already contains a list of controls. All you need to do is extract the TextBox controls from the other controls.

    Code:
    private void button1_Click(object sender, EventArgs e)
    {
      foreach (var textbox in Controls.Cast<object>()
          .Select(control => control as TextBox)
          .Where(textbox => textbox != null))
      {
        if (Convert.ToInt32(textbox.Text) % 2 == 0)
        {
          textbox.BackColor = Color.Green;
        }
      }
    }

  7. #7
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Looping through textboxes in C#

    ^Yes, that's a better, more flexible, solution.
    EDIT: But be careful if you want to select only a subset of the textboxes, you'll need some way to filter them.
    Last edited by TheGreatCthulhu; June 1st, 2016 at 05:07 AM.

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,173

    Re: Looping through textboxes in C#

    Quote Originally Posted by TheGreatCthulhu View Post
    ^Yes, that's a better, more flexible, solution.
    EDIT: But be careful if you want to select only a subset of the textboxes, you'll need some way to filter them.
    What I posted is okay for a student type solution, but for production code, I'd recommend going to something like an MVVM pattern (where the model binds to behaviors of the controls) rather than manipulating the controls directly.

  9. #9
    Join Date
    May 2016
    Posts
    10

    Re: Looping through textboxes in C#

    Hi Guys
    Thank you very much the last one did it, No quite .
    Sorry this error was thrown all of sudden (An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll)
    help highly appreciated
    My regards
    Last edited by leader2k; June 1st, 2016 at 03:10 PM.

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,173

    Re: Looping through textboxes in C#

    Quote Originally Posted by leader2k View Post
    Hi Guys
    Thank you very much the last one did it, No quite .
    Sorry this error was thrown all of sudden (An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll)
    help highly appreciated
    My regards
    When you post to the forum, please include the exact code and the line that an error occurs. Posting back that some snippet of code that you were given doesn't work isn't very helpful.

  11. #11
    Join Date
    May 2016
    Posts
    10

    Re: Looping through textboxes in C#

    Hi
    // if (Convert.ToInt32(textbox.Text) % 2 == 0) Here Where the error was thrown.and by the way i didn't change anything in the code cause i'm testing it as a stand alone.
    Thank you
    My regards

  12. #12
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,173

    Re: Looping through textboxes in C#

    Quote Originally Posted by leader2k View Post
    Hi
    // if (Convert.ToInt32(textbox.Text) % 2 == 0) Here Where the error was thrown.and by the way i didn't change anything in the code cause i'm testing it as a stand alone.
    Thank you
    My regards
    You need to understand that you are trying to convert a string into an integer and a requirement of this is whatever the string value is must be convertible. That means all text boxes need to have valid numeric values. If any of the textboxes are blank or don't contain a valid numeric value, you'll get an exception.

    Good code needs to handle these types of user situations. One way to validate that is each textbox contains a valid numeric value is to use Int32.TryParse.



    Code:
    private void button1_Click(object sender, EventArgs e)
    {
      foreach (var textbox in Controls.Cast<object>()
          .Select(control => control as TextBox)
          .Where(textbox => textbox != null))
      {
        var value = 0;
    
        if(Int32.TryParse(textbox.Text, out value))
        {
          if (value % 2 == 0)
          {
            textbox.BackColor = Color.Green;
          }
        }
        else
        {
           // TODO: display invalid textbox value
        }
      }
    }

  13. #13
    Join Date
    May 2016
    Posts
    10

    Re: Looping through textboxes in C#

    Hi
    you Nailed it.
    Thank you immensely for the help
    My regards

  14. #14
    Join Date
    May 2016
    Location
    Navi Mumbai
    Posts
    10

    Re: Looping through textboxes in C#

    Thanks for replying with the complete code.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)