Reputation: 6209
For a personal project I want to make a simple Inventory system in C#. There are three inputs, itemName(string), itemQuantity(int), itemLevelAlert(int), and then a button.
When the 'Add' button is clicked, I want the input data to be grouped and stored somewhere. I am not experienced in C# enough to know the best way to do this.
In JavaScript I'd probably use a multi-dimension array:
var inventoryArray = [["Hammer", 25, 5], ["Nails", 100, 20]]
and simply push the input to that array. I'm still learning C# and it goes about arrays a bit differently.
Could I do something similar with a list? I'm probably jumping into deep here considering my inexperience but I feel like I learn better that way.
Upvotes: 0
Views: 856
Reputation: 85
You can use string and int types doing the following:
(string, int, int)[] Cats =
{
("Tom", 20, 3), ("Fluffy", 30, 4), ("Harry", 40, 5), ("Fur Ball", 40, 6)
};
foreach (var cat in Cats)
{
Console.WriteLine($"My cats name is {cat.Item1} it is {cat.Item2} years old and weights {cat.Item3} lbs.");
}
Upvotes: 0
Reputation: 16310
You can start with defining your model :
internal class Inventory
{
public string ItemName { get; set; }
public int ItemQuantity { get; set; }
public int ItemLevelAlert { get; set; }
}
Then, you should declare list of inventory where you will store your newly created inventory :
var inventoryList = new List<Inventory>();
After that, you need to add your inventory in above inventoryList in button click event :
button.Click += (s, e) =>
{
inventoryList.Add(new Inventory()
{
// get value from your form
ItemName = "Item1",
ItemLevelAlert = 1,
ItemQuantity = 5
});
Upvotes: 1
Reputation: 416179
In .Net languages like C#, you typically want to build a type (class) for this kind of thing:
public class Item
{
public string Name {get;set;}
public int Quantity {get;set;}
public int AlertLevel {get;set;}
}
And then you create a generic List object that can hold these items (and only these items!)
var inventory = new List<Item>();
And now, when you click add, the code for the button looks something like this (assuming Winforms and with lots of made-up variable names. Web sites will look different):
//assuming Winforms. Code for a web site will look a bit different:
private void button1_Click(object sender, EventArgs e)
{
int quantity, alertlevel;
if (!int.TryParse(txtQuantity.Text, out quantity))
{
MessageBox.Show("Enter a valid number for the quantity.");
return;
}
if (!int.TryParse(txtQuantity.Text, out alertlevel))
{
MessageBox.Show("Enter a valid number for the alert level.");
return;
}
inventory.Add(new Item() {Name = txtName.Text, Quantity = quantity, AlertLevel = alertlevel});
}
Upvotes: 2