-1

I'm REALLY new to C# and programming overall, so my question might be stupid in your opinion but here it is.

I have created a form which contains 7 textboxes and i want to collect text from these textboxes and add them to a list. I however get an error saying, System.Windows.Forms.TextBox is a 'type' but is used like a 'variable". What should I do?

for (int i = 1; i < 8; i++)
{
    if (TextBox[i].Text == "")
    {
        days.Add("Restday");
    }
    else
    {
        days.Add(TextBox[i].Text);
    }   
}
Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Arvin Ashrafi
  • 621
  • 2
  • 7
  • 9

4 Answers4

3

TextBox is a type. so TextBox[i] is causing you trouble.

You can alway do something like this

foreach(Control ctrl in yourform.Controls)
{
    Textbox = ctrl as TextBox;
    if(txtBox != null)
    {
        if (txtBox.Text == "")
        {
            days.Add("Restday");
        }
        else
        {
            days.Add(txtBox.Text);
        } 
    }
}

This work for a basic form. If you have pannel and other container to organize your controls the approch described in Guffa answer might be better. This could also be rewritten as method who accept a collection of Control recursive use to reach all controls.

Community
  • 1
  • 1
Rémi
  • 3,867
  • 5
  • 28
  • 44
2

I guess you don't have an array named TextBox that is why the error. You can try following:

List<strig> days = this.Controls.OfType<TextBox>
                                .Select(r=> string.IsNullOrWhiteSpace(r.Text) 
                                            ? "Restday" : r.Text)
                                .ToList();

But the above would give you the textboxes added on the form directly, If these textboxes are inside other control then you can look for recursively

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
2

Put the textbox references in an array so that you can easily loop through them. If your textboxes are named TextBox1 to TextBox7:

TextBox[] boxes = {
  TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7
};

foreach (TextBox box in boxes) {
  if (box.Text == "") {
    days.Add("Restday");
  } else {
    days.Add(box.Text);
  }
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Go into the form editor and select one of your textboxes. Now find the properties window. If it's not visible then click View->Properties Window

One of the properties in there will be the name of the textbox control. Use that to access it's text value like so:

days.Add(txtMyTextboxName.Text);

If you must iterate through the textboxes you can do this:

foreach(var Textbox in this.Controls.OfType<TextBox>())
{
    if (Textbox.Text == "")
    {
        days.Add("Restday");
    }
    else
    {
        days.Add(Textbox.Text);
    }   
}

But bear in mind this is a pretty non-standard approach and not recommended.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147