|
-
August 6th, 2011, 07:26 AM
#11
Re: is the a C# equivalent to TextBox(i).Text =
NullReferenceException:
The line:
TextBox[] textBoxArray = new TextBox[10]; creates a new, empty array of TextBox-es.
When you write "textBoxArray[i]", you are accessing an element of the array, however, all elements are null so far (equivalent to Nothing in VB.NET).
For "textBoxArray[i].Text = "whatever";" to be able to work, "textBoxArray[i]" has to return an existing TextBox object.
The statement is basically equivalent to textBoxAtLocation_i.Text = "whatever";.
So, you need to put all the textboxes in the array before you can set the Text property.
Wich brings me to your other question.
My example:
I forgot something. The Add() method expects a TextBox, yet the textboxes it gets are all treated as Control-s (Control is on the inheritance chain of TextBox). They need to be type-cast back to TextBox.
Code:
// Assuming that all the textboxes are direct children to the containing form
// (i.e. some of them aren't on a special panel or some other container subelement)
List<TextBox> list = new List<TextBox>();
foreach(Control c in this.Controls)
{
//checks for a more specific type of c
if(c is TextBox)
list.Add((TextBox)c);
}
// now, assuming you have a TextBox[] member variable called _textBoxes
_textBoxes = list.ToArray();
That should do the trick.
Note: You want to do this only once - at the start (assuming you're not adding more textboxes at runtime). Maybe in the constructor of your form.
For this to work, the _textBoxes array (or textBoxArray in your example needs to be a member field of the Form1 class, so that it can be acessible to any of its methods.
Also, it's even more convenient to use a list instead of an array, as you can dynamically add and remove elements form it. Just use it's Count property in for-loops, or simply use foreach.
Last edited by TheGreatCthulhu; August 6th, 2011 at 07:32 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|