How To Add/Remove Items in c# Console Application Menu - c#

I'm wondering if I could use a few simple dictionaries to store the data behind this or if I need something more... Need a system to be able to add and remove items and have that translated to other menus (methods). Sorry if this is worded poorly
public int AddProducts(int customerIDinput)
{
//If the order already has 5 products then display an error that no more products can be added
//Prompts the user for a product ID
//If the user selects an invalid product then display an error
//If the user selects a product that is discontinued then display an error
//Prompt the user for a quantity
//If the user enters a value < 1 or > 100 then display an error
//Add the product and quantity to the order
//Display the updated order information
//Return to the main menu
int input;
input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please eneter a product ID:");
switch (customerIDinput)
{
case 1
break;
case 2
break;
case 3
break;
case 4
break;
case 5
break;
}
return customerIDinput;
}

You can use a generic List and switch the value entered by the user to be the INDEX Value of that list of products
a quick Example :
List<String> Products = new List<string>();
int Value = Int.Parse(Console.ReadLine());
switch(Value)
{
case 1:
if (Products.Item(1) == null)
Console.WriteLine("Doesnt Exist!"); // This check will be in all cases in the Default one of caus
break;
}
Or you can use that check in the first for example :
List<String> Products = new List<string>();
int Value = Int.Parse(Console.ReadLine());
if (Products.Items(Value) == null)
{
//Display Error
}
else
{
switch(Value)
{
case 1:
//what u want here
break;
}
}

Related

Using a sequencing variable to name a record?

I would like to use my variable i (that is used to sequence a loop) to name a record. This in order to know both how many of these records I have and to be able to loop through each one in a for loop.
This is how I have tried to do it:
while (UserValue != "none")
{
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
if (UserValue == "none")
break;
Console.WriteLine("Input this products value in Pounds.");
products i = new(UserValue, float.Parse(Console.ReadLine()));
i = i + 1;
}
I'm not even sure if it is possible so if it isn't, any alternative solution would be greatly appreciated.
It seems, that you want a collection, say List<T> of items, e.g.
//TODO: decimal is better if "value" stands for money
// I used named tuple here, but you may want an elaborated custom class
var products = new List<(string name, float value)>();
// Keep asking user to input products until "none" is given
while (true) {
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
//TODO: trim spaces and, probably, use case insensitive check
if (UserValue == "none")
break;
Console.WriteLine("Input this products value in Pounds.");
//TODO: float.TryParse is a better option
products.Add((UserValue, float.Parse(Console.ReadLine())));
}
then having collection you can loop over it:
for (int i = 0; i < products.Count; ++i) {
(string name, float value) = products[i];
...
}
or
foreach (var (name, value) in products) {
...
}
A better strategy is using a List<products>. Also, rename the products class to just product:
var allProducts = new List<product>();
// ...
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
if (UserValue == "none")
break;
Console.WriteLine("Input this product's value in Pounds.");
allProducts.Add(new product(UserValue, float.Parse(Console.ReadLine())));
You can still loop over this allProducts list with either a for loop (look at the .Count property of the list) or a foreach loop.

Else if statement inside for each loop - C#

I have a foreach loop like this where I want the else condition to output: "unit not found" if the quad.ID == searchForQuadcopters isn't found but I get this string value output even when the value is found.
foreach (var quad in allQuadcopters)
{
if (quad.ID == searchForQuadcopter)
{
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
WriteLine($"Capacity (kg): {quad.capacityKg}");
WriteLine($"Reach (km): {quad.reachKm}");
WriteLine($"Transponder ID: {quad.transponderID}");
quad.vehicleDeliveryForm();
}
else
{
WriteLine("Unit not found");
}
}
You won't know if the value isn't found unless you iterate over the ENTIRE list first and don't encounter it.
Create a boolean flag to track whether the value was found or not:
bool found = false;
foreach (var quad in allQuadcopters)
{
if (quad.ID == searchForQuadcopter)
{
found = true;
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
WriteLine($"Capacity (kg): {quad.capacityKg}");
WriteLine($"Reach (km): {quad.reachKm}");
WriteLine($"Transponder ID: {quad.transponderID}");
quad.vehicleDeliveryForm();
break; // if you don't want to iterate over the rest
}
}
if (!found) {
WriteLine("Unit not found");
}
I want the else condition to output: "unit not found" if the quad.ID == searchForQuadcopters isn't found
Then you don't want this loop. Your code loops over all items, and if allQuadcopters contains Ids 1, 2 and 3 and you're looking for 2, it will print "Unit not found" for Ids 1 and 3. You could break; out of the loop in your if(), but then the else will still be hit for 1.
You want to leverage Linq here:
var quad = allQuadcopters.FirstOrDefault(q => q.ID == searchForQuadcopters);
if (quad == null)
{
WriteLine("Unit not found");
}
else
{
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
}

Writing in List using switch c#

I wanted to insert data from textbox to list.
But whenever I am trying to gather to count the number of rows no rows are created. or no data are stored in the list
Here is the sample of the code.
foreach (classfile row in list)
{
switch (row.fld_ID)
{
#region Q1
case 1:
row.fld_Answer = QuestionTextBox1.Text.ToUpper().Trim();
break;
#endregion
#region Q2
case 2:
row.fld_Answer = QuestionTextBox2.Text.ToUpper().Trim();
}
}

C# Windows Forms how to change values of second combo box based on selection in first combo box

I am attempting to create an order form and as such am using combo boxes in order to let the user choose what item is going to be ordered. As such when the user selects the item that is going to be ordered, the second combo box should change to the sizes that the specific item can be ordered in. I have filled the second combo box with the sizes for all the items but I am unsure as to how to limit the sizes per the item that is selected. I have tried using if statements to addRange to the second combo box however this just duplicates the items at the end of the combo box. any help that can be given on this would be greatly appreciated. Thanks
private void itemBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (((ComboBox)sender).SelectedItem as string)
{
case "Name in a Frame":
sizeBox.SelectedIndex = 0;
break;
case "Scrabble Frame":
sizeBox.SelectedIndex = 1;
break;
case "Plaque":
sizeBox.SelectedIndex = 2;
break;
case "Hearts":
sizeBox.SelectedIndex = 3;
break;
case "Now and Forever Print":
sizeBox.SelectedIndex = 4;
break;
case "Pat cushion":
sizeBox.SelectedIndex = 5;
break;
case "Emilia cushion":
sizeBox.SelectedIndex = 6;
break;
}
}
private void sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (sizeBox.SelectedIndex == 0)
{
this.sizeBox.Items.AddRange(new object[]{
"7x5",
"10x8",
"A4",
"Mug"
});
}
}
You could just populate the sizeBox collection directly from the itemBox selected change event handler and remove sizeBox_SelectedIndexChanged altogether.
However, to achieve what, you need to clear the items in the sizeBox once the item has been selected. You can achieve this via:
sizeBox.Items.Clear();
You can then add the items once the sizeBox selected index has changed. I would simply use:
sizeBox.Items.Add("New Size");
For good practice I would remove the use of magic strings, maybe put them in a Products helper class that returns the appropriate string.

How do I print out error message if I enter an input that doesn't exist in Database? N-Tier

A quick brief explanation on my question: I want to my program to print out an error message without crashing the program if I enter a number that doesn't exist in my program's Database. Here is my code:
listBox1.Items.Clear();
BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf");
if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input.
{
listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!");
}
int N = System.Convert.ToInt32(this.txtMovieID.Text);
BusinessTier.Movie movie = BT.GetMovie(N);
BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows.
//display results:
listBox1.Items.Add(movie.MovieName);
foreach (BusinessTier.Review r in movieid.Reviews)
{
listBox1.Items.Add(r.UserID + ": " + r.Rating);
}
First thing : you are still processing the remaining part of the process, i.e retrieving the Movie Details, even if this.txtMovieID is null. You need to stop the processing and return
listBox1.Items.Clear();
BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf");
if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input.
{
listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!");
return; // exit out if the MovieID is null
}
Second : put a check to see whether the result of GetMovie(N) is null or not and if it is null, break and return
int N = System.Convert.ToInt32(this.txtMovieID.Text);
BusinessTier.Movie movie = BT.GetMovie(N);
if (movie == null) return; // exit if the GetMovie result is null
BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows.
//display results:
listBox1.Items.Add(movie.MovieName);
foreach (BusinessTier.Review r in movieid.Reviews)
{
listBox1.Items.Add(r.UserID + ": " + r.Rating);
}

Categories