Array of Textboxes

  • Thread starter Thread starter garak
  • Start date Start date
G

garak

Hi,

can anyone tell me what ist wrong with this code ?

TextBox[] txtField = new TextBox[4];
txtField[0].Text = "Hello";

I get the error :
An unhandled exception of type 'System.NullReferenceException'
occurred in PentaEngine.exe

Additional information: Object reference not set to an instance of an
object.


Thank you very much for you help.
Frank
 
This code initializes the array object, but does not initialize the array elements
TextBox[] txtField = new TextBox[4]

That is, when you tries to set the property value, the object txtField[0] doesn't exist, it's a null reference
txtField[0].Text = "Hello"

You must create the objects before using it. For example
txtField[0] = new TextBox()
 
Hello Frank,

You haven't actually created any TextBox objects, you've only created a
4-element TextBox array with each element initialised to null. You need to
assign a valid TextBox reference to the array elements, e.g.
txtField[0] = new TextBox();
etc.

I hope that helps.


garak said:
Hi,

can anyone tell me what ist wrong with this code ?

TextBox[] txtField = new TextBox[4];
txtField[0].Text = "Hello";

I get the error :
An unhandled exception of type 'System.NullReferenceException'
occurred in PentaEngine.exe

Additional information: Object reference not set to an instance of an
object.


Thank you very much for you help.
Frank
 
garak said:
can anyone tell me what ist wrong with this code ?

TextBox[] txtField = new TextBox[4];

That creates an array which can hold 4 TextBox references. It doesn't
create any actual TextBoxes. Each element in the array is null.
txtField[0].Text = "Hello";

That then dereferences the null to try to set the Text property - and
fails.

You need to do something like:

TextBox[] txtField = new TextBox[4];
for (int i=0; i < txtField.Length; i++)
{
txtField = new TextBox();
}
txtField[0].Text = "Hello";

(Note that this is not limited to TextBoxes - it's common to all arrays
of reference types.)
 
Back
Top