tags:

views:

74

answers:

4

im creating a list to update a MySql db with values form text boxes, how can i make somthing like this work?

if i use the

    verdierX[0] = (int)decimal.Parse(box1.Text);

it works just fine but when i try to use it in a loop like this is blowes up. Anyone got a suggestion on how to solve this?

    int[] dbNavnX = new int[8]; 
    int[] verdierX = new int[8];
    string[] boxList = new string[8];

    private void Form1_Load(object sender, EventArgs e)
    { 

        boxList[0] = "box1.Text";
        boxList[1] = "box2.Text";
        boxList[2] = "box3.Text";
        boxList[3] = "box4.Text";
        boxList[4] = "box5.Text";
        boxList[5] = "box6.Text";
        boxList[6] = "box7.Text";
        boxList[7] = "box8.Text";
    }

    private void sumX()
    {
        for (int sum = 0; sum < 8; sum++)
        {
            verdierX[sum] = (int)decimal.Parse(boxList[sum]);
        }
    }
+2  A: 

You should change your boxList array to hold references to the TextBoxes instead of strings:

TextBox[] boxList = new TextBox[8];

and

boxList[0] = box1;
boxList[1] = box2;
...

Then it will work.

M4N
thx mate just wat i was after :)
Darkmage
Silly me, I thought he wanted to write less code... Btw, he'll need to rewrite the sumX() method, because that one expects strings with the textboxes' contents...
Tor Haugen
A: 

If you're not using WPF, you can access the "me.controls" which is an array of all the controls available in your form. Watch out though, if your text box is on a panel or other container, you then use the object.controls to get the textbox.

Hope that works.

David Brunelle
+1  A: 

Try:

int[] verdierX = new int[8];

private void Form1_Load(object sender, EventArgs e)
{
    for (var i = 0; i < 8; i++)
    {
        TextBox tb = (TextBox)FindControl("box" + i.ToString());
        verdierX[i] = (int)decimal.Parse(tb.Text);
    }
}
Tor Haugen
ah even better, will try this.
Darkmage
The name 'FindControl' does not exist in the current context.what system namespace am i missing?
Darkmage
@Darkmage: Sorry, I thought you were doing ASP ;-) It's actually very similar (apart from the name Form1), and you didn't say.
Tor Haugen
+1  A: 

Or, how about some Linq goodness:

var sumX = from Control control in Controls
            where 
                control.GetType() == typeof (TextBox) 
                && control.Name.StartsWith("box")
            select Convert.ToInt32(((TextBox)control).Text);
Peter Lillevold
very nice, just what i need
Darkmage
works as long as you don't have any other TexBoxes whose name starts with "box"
M4N