Click here to Skip to main content
15,948,338 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm just learning c# and I have a form with 6 textbox controls. I need to click a button and save the contents of those controls to a two dimensional array because I need to be able to reference each row of the array later. My question is how do I save a row to an array, return to the form change the data, and click the save button and save to a different row?

What I have tried:

if (int.TryParse(txtExperimentNumber.Text, out index))
               if (index <= ROWS)
                   experiments[index, 0] = exp.Number.ToString();
                   experiments[index, 1] = exp.Name;
                   experiments[index, 2] = exp.Description;
                   experiments[index, 3] = exp.Volume.ToString();
                   experiments[index, 4] = exp.Weight.ToString();
                   experiments[index, 5] = exp.Color.ToString();
           lstSummary.Items.Add(exp.Number.ToString() + "\t" +
Updated 9-Oct-22 10:03am

Increment index either before you test for an available entry, or after you have filled the row.
Share this answer
The problem with an array is all the elements (rows and columns) have to be of the same type. I see that you are changing each of the data elements to strings so you have that covered. But, you might consider making a simple class that holds the data from the textbox controls. Each of the attributes of the class can be of the native type so you no longer need to convert data to strings to save and from strings to work with it. Now you only need a single dimensioned array of this new class type.

The next problem with an array is you need to manage allocating and expanding the array as you add rows. C# has a collection class called List that would work well for your case. It can be indexed directly like an array but you can add or insert rows as you need and it handles the allocation and expansion of the list as needed so you can concentrate on what to do with the data.

Now your code becomes:
class ExpData
    // TODO: Add your experiment data elements here.

// Declare your list:
    List expList = new List<ExpData>;
// Fill the text boxes, click to save.

// In the click event:
    ExpData exp = new ExpData(textbox1 value, ...);

When you need to work with the saved data you just get the class instance at the List index you want and do your thing.
Share this answer

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