Textbox access.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • poko
    New Member
    • Dec 2009
    • 16

    Textbox access.

    Hi. I am having difficulty looping through texboxes. I do not want to use Controls. I have named my textboxes as:

    textBoxBuy1, textBoxBuy2, textBoxBuy3, .....

    There are many more textboxes in the form (with different names so that I can use the desired ones in a loop) but I do not want to refer to them while looping. I want to loop all the textboxes named textBoxBuy only. This is what I am doing:

    for (int i = 1; i < 6; i++)
    {
    if ((TextBox)Contr ols["textBoxBuy " + i.ToString()].Text.Length != 0) {}
    }

    The error that I am getting is:

    Error 1 Cannot convert type 'int' to 'System.Windows .Forms.TextBox'

    Can someone please help me out with this?
    Thanks
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Sometimes it's good to break your lines down instead of trying to cram as much information as possible onto one line ;)

    Your problem is brackets. You're applying the cast to Text.Length instead of the control. The line should actually look like...

    Code:
    if (((TextBox)Controls["textBoxBuy" + i.ToString()]).Text.Length != 0) { }
    However, as I'm sure you've gathered by now this is a very difficult line to read and make sure you have correct. Maybe try something like the following... it's easier to read, and a little safer since it's quite possible that you don't find the control you're looking for with a text string.

    Code:
    for (int i = 1; i < 6; i++)
    {
        TextBox tb = this.Controls["textBoxBuy" + i.ToString()] as TextBox;
        if (tb != null && tb.Text.Length != 0)
        {
        }
    }

    Comment

    • poko
      New Member
      • Dec 2009
      • 16

      #3
      Thanks Gary, it worked. And I'll try to remember your tip :)

      Comment

      Working...