Using array in different methods [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
well i'm doing a code in C#,
this code allows you to add items to your code, price, unit, etc. save them in an array, and a menu will display the aggregated items.
I have a problem because I do it this way and apparently my code don't work, could someone help me?.
King Regards.
I'm newest in this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Market
{
public class Menu
{
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
public void showMenu()
{
Console.WriteLine("1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
//Menu
while (true)
{
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}
}

There are few problems with the code.
Arrays that you created for product, code, etc are of zero size as item value is by default. Inserting any value to 0 sized array throws an exception.
Also you should be cautious on accessing the static fields in not static context.
.
I would suggest define a class with these properties and use the List to keep collection.
public class Product
{
public string Name {get;set;}
public string Code {get;set;}
public double Price {get;set;}
public int Unit {get;set;}
}
Now modify your additem to create products.
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
var product = new Product();
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Name = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
product.Code = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
product.Price = double.Parse(Console.ReadLine()); //read as double value.
Console.Write("Unit[" + i + "]: ");
product.Unit = int.Parse(Console.ReadLine()); // Read as int value
products.Add(product); // products is global/class variable.
}
}
Check this Demo, it gives you an idea to proceed.

You are initializing yours arrays with a zero length. You arrays and item property are static that are initializing at application start. So when you change item field your arrays have already been initialized with default value of int, that is zero. You should initialize your arrays after setting the item property. And even after this you will not be able to add items to your arrays. Try to use List<> instead.

The issue is the static variable item is initialized to 0 when the class loads. Once you change it by reading in the user inputted value, you don't allocate properly sized arrays for your static variables. You can fix this by doing so after reading in the value:
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
// initialize static vars to correct size, now that we have #items
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
You can see the fixed code in action at https://dotnetfiddle.net/n5lWTQ !

Just to get you started... you instantiated your arrays in the field declaration with a size of item
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
The problem with this is that the moment you access the Menu class, these lines of code immediately gets executed. And since the default value of an int is 0, you will have your array sizes to be 0. Try applying breakpoints into those line and you'll see.
Now what you can do here is instantiate them once you have set the value of item. So you will have your code to be something like this...
public static int item { get; set; }
//just declare your arrays here
public string[] product;
public string[] code;
public string[] price;
public string[] unit;
public void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
//instantiate your arrays here since item will have a value you have set it into.
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");

You could try using a list of objects containing the required fields of your item. A generic list will allow you to dynamically add items to the list without having to set the size during initialization. This means you can add items (using option 1) as many times as you like without changing the arrays.
In addition to setting the arrays to zero size when you initialized your class (as other answers have suggested), it looked as if you were re-using your int item property each time you wanted to add new items to your lists. This means that the variable was changing so your ShowItems() method did not function correctly.
Here is a working example:
using System;
using System.Collections.Generic;
namespace Market
{
public class Menu
{
public struct Item
{
public string product;
public string code;
public string price;
public string unit;
}
public static List<Item> items = new List<Item>();
public static void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
int numbItemsToAdd = Convert.ToInt32(Console.ReadLine()); // needs validation
Console.WriteLine("Insert the items.");
for (int i = 0; i < numbItemsToAdd; i++)
{
Item item = new Item();
Console.WriteLine("\nItem[" + (i + 1) +"]: ");
Console.Write("Product[" + (i + 1) +"]: ");
item.product = Console.ReadLine();
Console.Write("Code[" + (i + 1) + "]: ");
item.code = Console.ReadLine();
Console.Write("Price[" + (i + 1) + "]: ");
item.price = Console.ReadLine();
Console.Write("Unit[" + (i + 1) + "]: ");
item.unit = Console.ReadLine();
items.Add(item);
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
foreach(Item i in items)
{
Console.WriteLine(i.product + " " + i.code + " " + i.price + " " + i.unit);
}
}
public static void Main()
{
showMenu();
}
}
}

public class Menu
{
public static int item { get; set; }
public static List<string> product = new List<string>();
public static List<string> code = new List<string>();
public static List<string> price = new List<string>();
public static List<string> unit = new List<string>();
public void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit \n");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 1; i <= item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Add(Console.ReadLine());
Console.Write("Code[" + i + "]: ");
code.Add(Console.ReadLine());
Console.Write("Price[" + i + "]: ");
price.Add(Console.ReadLine());
Console.Write("Unit[" + i + "]: ");
unit.Add(Console.ReadLine());
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}

Related

goto function alternative and multiple printed lines in results

Hoping someone can help. I'm still learning a lot each day as beginner. But have a few issues with the below.
The use of goto is a no-no from the research I have seen but I can't figure out an alternative loop to add while maybe? Or do?
When I enter text that I know will not return a result e.g. dsfgfhg and press enter I receive "Resource Not found " three times in the results. I assume this is because out of the list there are three entries and none match. How do I get one result instead of three when a resource is not found?
If I press enter twice in the console window without entering any text it returns everything in the list. Again I can't see a way to stop this. I guess I need to change the code to be explicit in some way?
Thanks again for your help.
using System;
using System.Collections.Generic;
class JunkList
{
public string Resource { get; set; }
public string Junk { get; set; }
public int Amount { get; set; }
public JunkList(string r, string j, int a)
{
this.Resource = r;
this.Junk = j;
this.Amount = a;
}
}
class Program
{
static void Main(string[] args) // this is a method called "Main" . It is called when the program starts.
{
start:
string searchName;
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
Console.WriteLine("Which resource do you want to search for?? \n");
searchName = Console.ReadLine();
for (int i = 0; i < infoList.Count; i++)
{
if (infoList[i].Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
Console.WriteLine("Resource : " + infoList[i].Resource + "\n");
Console.WriteLine("Junk : " + infoList[i].Junk + "\n");
Console.WriteLine("Resource Amount : " + infoList[i].Amount + "\n");
}
else {
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
}
// wait for user to press a key. Then make an empty space and start over.
Console.ReadKey();
Console.WriteLine();
goto start; // go to start and run again
}
}
I recommend you to use 'single responsibility principle'. In your case that means that you should split your Main method into smaller methods. These methods do one simple action, i.e. responsibility.
Well, it will help:
You are right goto quite often is a bad practice (but not always). Put your code into while(true) and it would do the same but more clear. However, to close your application correctly receiving some char or key to exit would be better, e.g.
bool _runApplication = true;
while (_runApplication)
{
// code between "start:" and "goto start;"
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
To solve this multiple Resource Not found output you can separate searching by name and printing searching results, e.g.
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
foreach (var junkList in searchResult)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
where new method is:
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
It is because of searchName is equal to en empty string. Add a simple if to solve it.
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
Applying all these points you will get code like this (only Program class modified):
class Program
{
static void Main(string[] args)
{
bool _runApplication = true;
while (_runApplication)
{
List<JunkList> infoList = CreateJunkList();
Console.WriteLine("Which resource do you want to search for?? \n");
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
PrintJunkLists(searchResult);
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
Console.WriteLine();
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
}
private static List<JunkList> CreateJunkList()
{
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
return infoList;
}
private static void PrintJunkLists(List<JunkList> junkLists)
{
foreach (var junkList in junkLists)
{
PrintJunkList(junkList);
}
}
private static void PrintJunkList(JunkList junkList)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
}
I hope it helped)

write objects from array to text file c# [duplicate]

This question already has answers here:
StreamWriter.Write doesn't write to file; no exception thrown
(8 answers)
Closed 4 years ago.
This C# assignment is about creating groups for salesmen at diffrent levels depending how much they sold for, and then write this info to a textfile using a streamwriter.
I have done all parts except the streamwriter part. What i do so far is to create the file, but there is no ouput.
When i run this the content in the console is correct but the textfile becomes modified but blank.
The streamwriter is in the bottom part.
´
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inlämningsuppgift2
{
// Emplooyeklassen where names, personal info, district och sold items sparas och hämtas
class Emplooye
{
String namn;
int personnummer;
string distrikt;
int såldaartiklar;
int säljnivå;
public Emplooye(string namn, int personnummer, string distrikt, int såldaartiklar)
{
this.namn = namn;
this.personnummer = personnummer;
this.distrikt = distrikt;
this.såldaartiklar = såldaartiklar;
}
public string Name
{
get { return namn; }
set { namn = value; }
}
public int PersonNummer
{
get { return personnummer; }
set { personnummer = value; }
}
public string Distrikt
{
get { return distrikt; }
set { distrikt = value; }
}
public int AmountSold
{
get { return såldaartiklar; }
set { såldaartiklar = value; }
}
public int SäljNivå
{
get { return säljnivå; }
set { säljnivå = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inlämningsuppgift2;
using System.IO;
namespace ConsoleApp3
{
class Säljlista
{
static void Main(string[] args)
{
List<Emplooye> ObjSeller = new List<Emplooye>();
List<Emplooye> group1 = new List<Emplooye>();
List<Emplooye> group2 = new List<Emplooye>();
List<Emplooye> group3 = new List<Emplooye>();
ObjSeller.Add(new Emplooye("Oscar Norberg", 961111, "Täby", 140));
ObjSeller.Add(new Emplooye("jonas okembia", 970912, "Uppsala", 70));
ObjSeller.Add(new Emplooye("Mille vega", 981212, "Danderyd", 40));
ObjSeller.Add(new Emplooye("Isak friisjespesen", 991132, "Skåne", 80));
ObjSeller.Add(new Emplooye("Maja olofsson", 974132, "Täby", 123));
ObjSeller.Add(new Emplooye("Annmarie norberg", 944432, "Täby", 230));
ObjSeller.Add(new Emplooye("Ulla persson", 9312332, "Uppland", 124));
ObjSeller.Add(new Emplooye("Christer Nilsen", 9988332, "Vallentuna", 444));
Console.WriteLine("Namn Personnummer Distrikt Antal");
//Here the employees gets sorted in groups depending how much they sold for.
foreach (Emplooye e in ObjSeller)
{
if (e.AmountSold > 0 && e.AmountSold <= 90)
{
group1.Add(e);
}
else if (e.AmountSold > 90 && e.AmountSold <= 200)
{
group2.Add(e);
}
else
{
group3.Add(e);
}
}
group1.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group1.Count; i++)
{
string name = group1.ElementAt(i).Name;
int pnr = group1.ElementAt(i).PersonNummer;
String district = group1.ElementAt(i).Distrikt;
int amountsold = group1.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 1" + ": " + group1.Count);
Console.WriteLine("");
group2.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group2.Count; i++)
{
string name = group2.ElementAt(i).Name;
int pnr = group2.ElementAt(i).PersonNummer;
String district = group2.ElementAt(i).Distrikt;
int amountsold = group2.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 2 2" + ": " + group2.Count);
Console.WriteLine("");
group3.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group3.Count; i++)
{
string name = group3.ElementAt(i).Name;
int pnr = group3.ElementAt(i).PersonNummer;
String district = group3.ElementAt(i).Distrikt;
int amountsold = group3.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 3" + ": " + group3.Count);
Console.WriteLine("");
StreamWriter SW = new StreamWriter("important.txt");
foreach(Emplooye i in group1)
{
SW.WriteLine(group1.ToString());
foreach(Emplooye i in group2)
{
SW.WriteLine(group2.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(group3.ToString());
}
}
}
You aren't closing the stream writer so it is buffering the output in memory but not writing to the file. Try a 'using' statement:
using(StreamWriter SW = new StreamWriter("important.txt"))
{
foreach(Emplooye i in group1)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group2)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(i.ToString());
}
}

Getting rank for baby name popularity ranking program

I'm trying to get this program finished but keep running into issues, I can't figure out how to get the count for ranking for the result I keep getting 1 for my output and I'm trying to get this finished as soon as I can. The output should look something like this :
Enter the directory path of the data files: C:\Intel
Enter the year:2010
Enter the gender (M/F): M
Enter the name: Javier
Javier is ranked #190 in year 2010
namespace QuestionTwo
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.Write("Enter the directory path of the data files: ");
string filename = Console.ReadLine();
filename.Replace(#"\", #"\\");
Console.Write("Enter the year: ");
string year = Console.ReadLine();
Console.Write("Enter the gender (M/F): ");
string gender = Console.ReadLine();
Console.Write("Enter the name: ");
string name = Console.ReadLine();
filename += "\\yob" + year + ".txt";
string line = "";
try
{
using (StreamReader fin = new StreamReader(filename))
{
while((line = fin.ReadLine()) != null)
{
string[] parsed = line.Split(',');
if (parsed[1] == gender)
{
names.Add(parsed[0]);
}
}
}
for (int i = 0; i < names.Count; i++)
{
if (names[i] == (name))
{
Console.WriteLine(name + " is ranked #" + i + " in year " + year);
}
else //if (names[i] != (name)) // it is a logic error somewhere here
{
Console.WriteLine("The name " + name
+ " is not ranked in year " + year);
}
}
}
catch(Exception e )
{
Console.WriteLine("The file at {0} could not be read."+ e, filename);
}
for(int c = 0; c < names.Count; c++)
{
Console.WriteLine((c + 1) + ". " + names[c]);
}
Console.ReadKey();
}
}
}
Your program outputs too much because you are printing "The name " + name
+ " is not ranked in year " + year" for each name that doesn't match.
You need to add a flag to record whether you found the name while looking through the list, something like this: note I have also added a break keyword - once you've found the name, there's no need to continue looking.
You also need to subtract 1 from i to the output as your list starts from 0 and I expect you don't want a zero-based rank?
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
string filename = #"c:\temp\baby.txt";
string year = "1997";
string gender = "F";
string name = "Margaret";
string line = "";
try
{
using (StreamReader fin = new StreamReader(filename))
{
while((line = fin.ReadLine()) != null)
{
string[] parsed = line.Split(',');
if (parsed[1] == gender)
{
names.Add(parsed[0]);
}
}
}
bool foundName = false;
for (int i = 0; i < names.Count; i++)
{
if (names[i] == (name))
{
Console.WriteLine(name + " is ranked #" + i-1 + " in year " + year);
foundName = true;
break;
}
}
if (!foundName)
{
Console.WriteLine("The name " + name
+ " is not ranked in year " + year);
}
}
catch(Exception e )
{
Console.WriteLine("The file at {0} could not be read."+ e, filename);
}
for(int c = 0; c < names.Count; c++)
{
Console.WriteLine((c + 1) + ". " + names[c]);
}
Console.ReadKey();
}
}
Output:
Margaret is ranked #4 in year 1997
The name Doris is not ranked in year 1997
Notes:
Your search is case-sensitive so "margaret" doesn't match
Your gender check is also case-sensitive so "f" doesn't find a match

Field 'xxx' is never assigned to, and will always have its default value null

My error:
Field 'StockManagement.LargeItems1.largeS' is never assigned to, and will always have its default value null
My code:
namespace StockManagement
{
class LargeItems1
{
private Stack<string> largeS;
public LargeItems1()
{
Stack<string> largeS = new Stack<string>();
}
public void LargeItemsAdd()
{
string usersInput2, tempValue;
int tempValueI = 0;
bool attempt = false;//, whichOne = false;
Console.WriteLine("Would you like to remove or add an item to the storage area \n Reply add OR remove");
string usersInput = Console.ReadLine();
usersInput = usersInput.ToLower();
if (usersInput.Contains("remove"))
{
LargeItemsRemove(largeS);
return;
}
else if (usersInput.Contains("add"))
{
Console.WriteLine("Please input (numerically) how many IDs you'd like to add");
tempValue = Console.ReadLine();
attempt = int.TryParse(tempValue, out tempValueI);
while (!attempt)
{
Console.WriteLine("Please input (numerically) how many IDs you'd like to add, you did not input a numeric value last time");
tempValue = Console.ReadLine();
attempt = int.TryParse(tempValue, out tempValueI);
}
for (int i = 0; i < tempValueI; i++)
{
Console.WriteLine("Please input the ID's (one at a time) of the item you would like to add");
usersInput2 = Console.ReadLine();
if (largeS.Contains(usersInput2))
{
Console.WriteLine("That ID has already been stored");
}
else
{
largeS.Push(usersInput2);
}
}
foreach (var item in largeS)
{
Console.WriteLine("Current (large) item ID's: " + item);
}
}
}
public void LargeItemsRemove(Stack<string> largeS)
{
if (largeS.Contains(null))
{
Console.WriteLine("No IDs stored");
}
else
{
string popped = largeS.Pop();
foreach (var item in largeS)
{
Console.WriteLine("Pop: " + item);
}
Console.WriteLine("Removed ID = " + popped);
}
}
}
}
I don't understand how to assign my values to the instances. I'd appreciate any help that can be provided!
Change your constructor to initialize the field instead of the local variable:
public LargeItems1()
{
this.largeS = new Stack<string>();
}
You have to initialize your field largeS, using the this keyword, in this way:
this.largeS = new Stack<string>();
The this keyword is used to refer to the current instance of the class. If you use instead:
Stack<string> largeS = new Stack<string>();
you're just initializing a new local variable that has nothing to do with your private field.
Check the MSDN documentation about this keyword.

How to allow CRUD operations in a DataGridView in C#.NET?

I've been having a lot of trouble to bind a database (I'm using Northwind) to a DataGridView.
I've tried various approaches, but none worked for all operations, only some.
I've also asked on other sites, but so far I haven't gotten any helpful advice.
Is there a tutorial that covers really all CRUD operations (or a combination of several tutorials that together cover all)?
Especially the delete operation is causing me headaches as the only tip I've gotten is to put my delete code into some DataGridView event, yet the problem is that I cannot find a way to determine what exactly the user wants to delete and the KeyDown event won't fire for the delete key.
Thanks!
EDIT:
Thank you very much. That document is very helpful.
I have another question though, I have a DataTable as DataSource for the DataGridView.
To update it for execution of user input CRUD operations, do I need to manually insert data into the DataTable or is it enough to just built a regular SQL command with the adapter's DeleteCommand/InsertCommand/etc properties and then just pass the yet unmodified DataTable as argument in the Update method?
I.e. would this get me the desired result of insert a new row into the db table with the values the user has just input into the DataGridView?
private void DGV_Nwind_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
string sql = "INSERT INTO [" + table.TableName + "] VALUES ("; //sql command base
//add values to command
for (int i = 0; i < e.Row.Cells.Count; i++)
{
sql += "'" + e.Row.Cells[i].ToString() + "'";
if (i < (e.Row.Cells.Count - 1))
{
sql += ", ";
}
else
{
sql += ")";
}
}
//update table
con.OleAdapter.InsertCommand = new OleDbCommand(sql);
con.OleAdapter.Update(table);
}
I've created a C# Lib & App, that let's you create your object, CRUD operations (using BLL & DAL) and Web UI to perform that CRUD operations.
http://manacodegenerator.codeplex.com
It's lightweight and pretty straightforward to use, it helped me get rid of those boring hours of repetitive code creation.
I'm constantly evolving it since it's a tool that I use on a daily basis.
Hope it helps!
If you are using a WPF application, here is a tutorial for how to do CRUD operations:
http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx#updates
Basically, you would tie into the row deleted event and in your method you would process the deleted row.
Here is a doc on using the DataGridView. In it is information on tying into the Delete event and other CRUD operations:
http://www.windowsclient.net/Samples/Go%20To%20Market/DataGridView/DataGridView%20FAQ.doc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Projecttest
{
class Program
{
struct student
{
public string stid;
public string stname;
public string stage;
};
static void Main(string[] args)
{
student[] st = new student[4];
int choice;
string confirm;
int count = 0;
Console.WriteLine("Select operation to Perform");
Console.WriteLine("1. ADD");
Console.WriteLine("2. UPDATE");
Console.WriteLine("3. DELETE");
Console.WriteLine("4. SHOW");
do
{
Console.Write("enter your choice(1-4):");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Add(st, count);
count++;
break;
case 2:
Update(st);
break;
case 3:
Delete(st);
break;
case 4:
Show(st);
break;
default:
Console.WriteLine("\nInvalid Selection\n");
break;
}
Console.Write("Press Y or y to continue:");
confirm = Console.ReadLine().ToString();
} while (confirm == "Y" || confirm == "y");
}
static void Add(student[] st, int count)
{
Console.Write("\nEnter student ID: ");
st[count].stid = Console.ReadLine();
Console.Write("Enter student name: ");
st[count].stname = Console.ReadLine();
Console.Write("Enter student age: ");
st[count].stage = Console.ReadLine();
}
static void Show(student[] st)
{
for (int count = 0; count < st.Length; count++)
{
if (st[count].stid != null)
{
Console.WriteLine("\nStudent ID : " + st[count].stid);
Console.WriteLine("Student Name : " + st[count].stname);
Console.WriteLine("Student Age : " + st[count].stage);
}
}
}
static void Delete(student[] st)
{
Console.Write("\nEnter student ID: ");
string studid = Console.ReadLine();
for (int count = 0; count < st.Length; count++)
{
if (studid == st[count].stid)
{
st[count].stid = null;
st[count].stname = null;
st[count].stage = null;
}
}
}
static void Update(student[] st)
{
Console.Write("\nEnter student ID: ");
string studid = Console.ReadLine();
for (int count = 0; count < st.Length; count++)
{
if (studid == st[count].stid)
{
Console.Write("Enter student name: ");
st[count].stname = Console.ReadLine();
Console.Write("Enter student age: ");
st[count].stage = Console.ReadLine();
}
}
}
}
}

Categories

Resources