Reputation: 7
my problem probably has a simple solution, but I am just not grasping it. Here's the situation, I wish to register a vehicle through several characteristics that are input in textboxes and so on, by the user, and stored in an array, so that he can then look up a vehicle, or alter certain characteristics of said vehicle.
Breaking it down in two-steps:
int aSize = Convert.ToInt32(numericUpDown1.Value);
int[] Viaturas;
Viaturas = new int[aSize];
Assuming the first point is OK, the second one is where I struggle, I have no idea how to code this. Any ideas?
Thanks in advance!
Upvotes: 0
Views: 1142
Reputation: 3001
I agree with bwoogie - use a strongly typed object for this, and use a list if you can. This sample shows how to add a new vehicle when the user fills out the form and clicks a button. It has samples in there for either an array or a list. Note that both the array and the list can be passed into the same method, which expects an array of vehicles:
// you should be able to use a list...
List<Vehicle> list = new List<Vehicle>();
// or if you must use an array
Vehicle[] array; // initialize it like you do in your example
int arrayPosition = 0;
private void button1_Click(object sender, EventArgs e)
{
// create an instance of a strongly typed object using your textboxes, etc.
Vehicle v = new Vehicle();
v.Make = textBoxMake.Text;
v.PurchaseDate = dtpickerPurchaseDate.Value;
v.Engine = comboBoxEngine.SelectedText;
// add the strongly typed object to a list
list.Add(v);
// or if you must use an array
array[arrayPosition] = v;
arrayPosition++;
// you can call a method that expects an array even if you are using a list
DoStuffWithTheArray(list.ToArray());
// or if you must use an array
DoStuffWithTheArray(array);
}
private void DoStuffWithTheArray(Vehicle[] array)
{
// expects an array of vehicles, but you can call it with a list or an array.
}
Upvotes: 0
Reputation: 4427
It sounds like you want to create an object to store all the data in.
public class Vehicle {
public Vehicle(string make...) {
Make = make;
...
}
public string Make;
public string Model;
public string Year;
public string Color;
...
}
Then you can use a List
to store all vehicles, it will handle the size of the array for you:
List<Vehicle> Vehicles = new List<Vehicle>();
Vehicles.Add(new Vehicle(textboxMake.Text, ...));
And access them like:
textboxMake.Text = Vehicles[0].Make;
Upvotes: 1