Click here to Skip to main content
15,041,391 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I just started university and am currently learning to program. We've started learning about arrays and i've been a bit lost on how to implement this on a WinForm application. This is what I have so far but it does not work at all and i'm wondering if I could receive a bit of help on how to solve this issue. So basically I have a WinForm with a single button and a single textbox. I have a 2d array that is [3,5] and what I want to happen is have the user input a number in the textbox, click the button and that value would be stored at [0,0], the textbox would then clear, have the user input another number, and that would be saved in [0,1], etc. When the first row is filled it would then start saving on the next row [1,0] and so on. Thanks a lot for any help given.

What I have tried:

public partial class Form1 : Form
        int[,] array2d = new int[3, 5];
        int row = 0;
        int col = 0;
        public Form1()

        private void btnArray_Click(object sender, EventArgs e)
            for(row = 0; row < 3; row++)
                for(col = 0; col < 5; col++)
                    array2d[row, col] = int.Parse(txtBoxArrays.Text);
Updated 12-Nov-20 10:57am

1 solution

In Windows apps, you don't loop inside event handlers like your button click event, because it will not do what you are used to in a Console app - they work very differently.

Instead of telling the user what to do and when by using WriteLine and ReadLine, you respond to what the user does do via events. The user clicks a button, you get an event. Your handler reads the text box content, stores it in the array, and "goes back to sleep" until the user presses the button again, indicating he number in the textbox is what he wants stored this time.

So dump the for loops, and instead read a single value and store it.
1) Get the value from the TextBox.Text property.
2) Use int.Parse (if you must - int.TryParse would be more user friendly) to convert it to a number.
3) Store the number in the array at [row, col].
4) Advance col to the next column, and check if you need to reset col and change row instead.
5) Return from the event handler method.

Give it a try - it's pretty simple when you get your head round it (easier than Console apps most of the time!) - it's just the initial conceptual step that you have to work out in and change your thinking.
Enerus 12-Nov-20 16:13pm
I see, this helped a lot and i'm starting to make progress on my application. Thank you so much!
OriginalGriff 12-Nov-20 16:29pm
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900