c# textbox array

Soldato
Joined
30 Nov 2005
Posts
13,916
I have 10 textboxes that I want to read into an array to then work some calculations on, I can do this the long way but unsure on how to loop through the textboxes on a button click event.
Code:
for example


int[] MyArray = new int[3]
MyArray[0] = textbox1.text;
MyArray[1] = textbox2.text
MyArray[2]= textbox3.text

sorry if this a stupid question.
 
ok its still not quite right but whats wrong?


private void calcButton_Click(object sender, EventArgs e)
{
double[] arr = new double[10];
for (int i = 0; i <= 10; i++)
{
TextBox curText = (TextBox)this.Controls["amt" + i.ToString()];
arr = double.Parse(curText.Text);


}
}



getting this error

System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=lab1
StackTrace:
at lab1.Form1.calcButton_Click(Object sender, EventArgs e) in C:\Documents and Settings\jay\My Documents\Visual Studio 2010\Projects\lab1\lab1\Form1.cs:line 60
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at lab1.Program.Main() in C:\Documents and Settings\jay\My Documents\Visual Studio 2010\Projects\lab1\lab1\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
 
Last edited:
Your code is trying to read amt0, amt1, amt2, ..., amt9, amt10 (11 elements). You said you only had 10 so you'll be calling .text on a null object, you're also overflowing the arr array.
 
As PaulM has said, you've come a cropper due to 0 index (10 boxes = 0 to 9), so you need to change the '<=' to '<'. Another option, if the texts boxes you want to read in are in their own panel (the only text boxes in that panel) you can do some nice linq.

So, if you wanted to add them all up and they are in a panel called 'pnlBoxes' you could:
pnlBoxes.Controls.OfType<Textbox>.Where(t => !string.isnullorempty(t.text)).select(t => double.parse(t.text)).Sum();

Would sum all the values in a text box or
pnlBoxes.Controls.OfType<Textbox>.Where(t => !string.isnullorempty(t.text)).select(t => double.parse(t.text)).ToList();

would create a list with all the double values in.

Linq - very powerful and will impress your tutor :)
 
A way of doing this without Linq is to add a Panel like Goksly says, then move your textboxes to the panel. You can then just loop through all the controls on the panel, double checking that they are textboxes.

Say your new panel is called Panel1...

Code:
private void calcButton_Click(object sender, EventArgs e)
{
   List<double> arr = new List<double>();

   foreach (Control nextControl in this.Panel1.Controls)
   {
      if (nextControl.GetType() == typeof(TextBox))
      {
         arr.Add(Double.Parse((nextControl as TextBox).Text));
      }
   }

   // The arr collection now contains all the doubles.  It can be converted to
   // a plain array using arr.ToArrray() if required.
}

Keep in mind that this will break if you try to enter anything which isn't a number into the textboxes. You might want to either catch the exception or use Double.TryParse() to deal with that...
 
Back
Top Bottom