-1

I am pretty new to C#, I have been searching for an hour or so now for what I need and can't find it. I am trying to look at the contents of 32 different text box's using for loops. The code I have at the moment is:

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        string ElementString;
        Control ElementControl;
        double Num;
        Boolean errorMsg = false;

        for (int x = 1; x <= 4; x++)
            for (int y = 1; y <= 4; y++)
            {
                ElementString = "txtA" + x.ToString() + y.ToString();
                ElementControl = this.Controls[ElementString];
                ElementString = ElementControl.Text.Trim();

                if (!double.TryParse(ElementString, out Num))
                {
                    errorMsg = true;
                    break;
                }
            }

        if (errorMsg)
            MessageBox.Show("Error Processing Input Matricies, invalid entries");
    }

Ok changing this part, sorry for not putting more information, but hopefully this will help.

The program crashes when the button is clicked. It crashes when running the line:

ElementString = ElementControl.Text.Trim();

And gives the error message: Object reference not set to an instance of an object.

Thank you

JBurnham
  • 57
  • 8
  • 5
    "it doesnt work" (sic) is *never* enough information. Please read http://tinyurl.com/so-list – Jon Skeet Jan 16 '14 at 14:01
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – John Willemse Jan 16 '14 at 14:21

2 Answers2

1

The first thing you need to do is check if ElementControl is null. Do that right before you call the line that is throwing the exception.

Another way to do this would be to search for all of the TextBox controls in your container and check them that way. You can use the following to do that:

foreach(Control c in this.Controls)
{
    if (c is TextBox)
    {
        // Do whatever you want to do with your textbox.
    }
}

That is much more dynamic than trying to call retrieve the controls by name.

joe_coolish
  • 6,953
  • 13
  • 59
  • 108
0

put an if statement around the part where it crashes:

if(ElementControl != null)
{
  ElementString = ElementControl.Text.Trim();
}
else
{
 //Handle error if element control is null
}
JBurnham
  • 57
  • 8