I've been tasked with a project where I have to use c# to create forms that digest a list of objects from a file, and is then able to pass the list to another window.
public class Food
{
public string Name;
public string Category;
public int Price;
}
public class Ingredient
{
public string Name;
public string Category;
public decimal PricePerUnit;
public decimal Quantity;
public Ingredient(string pName, string pCategory, decimal pPricePerUnit, decimal pQuantity)
{
Name = pName;
Category = pCategory;
PricePerUnit = pPricePerUnit;
Quantity = pQuantity;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Ingredient> Inventory = CallInventoryFile();
}
private void inventoryButton_Click(object sender, RoutedEventArgs e)
{
InventoryWindow wnd = new InventoryWindow();
wnd.ShowDialog();
}
public List<Ingredient> CallInventoryFile()
{
List<Ingredient> ProcessedInventory = new List<Ingredient>();
try
{
string[] fileLines = File.ReadAllLines("Inventory.txt");
//Reading in the file
for (int i = 0; i < fileLines.Length; i++)
{
string[] CurrentLine = fileLines[i].Split(',');
string Name = CurrentLine[0].Trim();
string Category = CurrentLine[1].Trim();
decimal PricePerUnit = decimal.Parse(CurrentLine[2].Trim());
decimal Quantity = decimal.Parse(CurrentLine[3].Trim());
Ingredient IngredientToAdd = new Ingredient(Name, Category, PricePerUnit, Quantity);
ProcessedInventory.Add(IngredientToAdd);
}
return ProcessedInventory;
}
catch
{
//if we get here read in failed
MessageBox.Show("There was an error reading in the file");
return ProcessedInventory;
}
}
Which I then have to move onto this window
public InventoryWindow()
{
InitializeComponent();
categoryComboBox.Items.Add("All");
categoryComboBox.Items.Add("Pizza");
categoryComboBox.Items.Add("Burger");
categoryComboBox.Items.Add("Sundry");
categoryComboBox.SelectedValue = "All";
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void categoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
My question is how can i pass the results of Inventory from MainWindow to InventoryWindow.
You can just pass inside the constructor ,
InventoryWindow wnd = new InventoryWindow(Inventory);
wnd.ShowDialog();
Then,
public InventoryWindow(List<Ingredient> inputList)
{
}
Related
I want to store Objects of the class Rezept in the list List RezepteListe. After that I want to filter that RezepteListe regarding their NameID. But obviously I dont get the Filter() Method run on my RezepteListe.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public List<Rezept> RezepteListe = new List<Rezept>();
private void button1_Click(object sender, EventArgs e)
{
Rezept Kartoffelsalat = new Rezept("Kartoffelsalat");
textBox1.Text = Kartoffelsalat.NameID;
RezepteListe.Add(Kartoffelsalat);
textBox1.Text = RezepteListe.Where(x => x.NameID == "Kartoffelsalat");
List<String> liste2 = new List<string>();
liste2.Add("Hallo");
textBox1.Text= liste2.Find(x => x == "Hallo");
}
}
public class Rezept
{
public List<string> Zutat { get; set; }
public string NameID { get; set; }
public Rezept(string NameID)
{
this.NameID = NameID;
}
}
i am updating my question to this
i created new class Student
class Student
{
private string _firstName;
private string _lastName;
private int _exam1;
private int _exam2;
private int _exam3;
private int _finalExam;
// First Name Property
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
//Last Name Property
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
//Exam 1 Property
public int Exam1
{
get { return _exam1; }
set { _exam1 = value; }
}
// Exam 2 Property
public int Exam2
{
get { return _exam2; }
set { _exam2 = value; }
}
//Exam 3 Property
public int Exam3
{
get { return _exam3; }
set { _exam3 = value; }
}
//Final Exam Property
public int FinalExam
{
get { return _finalExam; }
set { _finalExam = value; }
}
}
}
this is my add new student form class with one method to add new student
public class AddStudent : Form
{
StudentForm stu = null;
public AddStudent()
{
InitializeComponent();
stu = new StudentForm();
stu.Show();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// split the name into first and last name
string[] name = txtName.Text.Split(',');
Student std = new Student();
std.FirstName = name[0];
std.LastName = name[1];
std.Exam1 = Int32.Parse(txtExam1.Text);
std.Exam2 = Int32.Parse(txtExam2.Text);
std.Exam3 = Int32.Parse(txtExam3.Text);
std.FinalExam = Int32.Parse(txtFinal.Text);
stu.addItem(std);
this.Hide();
}
}
}
and this is my main form it has listbox to display list of students
public class StudentForm : Form
{
public StudentForm()
{
InitializeComponent();
}
public List<Student> students = new List<Student>();
public void addItem(Student std)
{
students.Add(std);
// it always show me 1 item in list
MessageBox.Show(students.Count.ToString());
}
}
Here's how your code is progressing, with comments added and irrelevant code removed:
private void btnSubmit_Click(object sender, EventArgs e)
{
...
// create a _new_ Student form
Student std = new Student();
...
// Add the student form to itself (huh?)
std.addItem(std);
// hide this form
this.Hide();
// show the new form
std.Show();
}
So you are always showing a new form with one item - the one that was just created.
Yeah that's cause in your btnSubmit_Click every time you are creating a new instance of the form Student and calling the addItem() method.
You rather move this field to a separate class like
public class Data
{
private string _firstName;
private string _lastName;
private int _exam1;
private int _exam2;
private int _exam3;
private int _finalExam;
}
have the form instance created in the start up like
public partial class AddStudent : Form
{
Student stu = null;
public AddStudent()
{
InitializeComponent();
stu = new Student();
stu.Show();
}
Change the list in Form1
public List<Data> students = new List<Data>();
In button click just add the Data instance like
private void btnSubmit_Click(object sender, EventArgs e)
{
// split the name into first and last name
string[] name = txtName.Text.Split(',');
Data std = new Data();
std.FirstName = name[0];
std.LastName = name[1];
std.Exam1 = Int32.Parse(txtExam1.Text);
std.Exam2= Int32.Parse(txtExam2.Text);
std.Exam3 = Int32.Parse(txtExam3.Text);
std.FinalExam = Int32.Parse(txtFinal.Text);
stu.addItem(std);
this.Hide();
}
This is because you're creating the Student form each time using this line:
Student std = new Student();
So every time you're clicking submit, you're creating a new Student form which creates a new empty public List<Student>
You need to seperate your model (Student) from your UI (StudentForm) and (AddStudentForm):
public class Student
{
public string FirstName { set; get; }
private string LastName { set; get; }
private int Exam1 { set; get; }
private int Exam2 { set; get; }
private int Exam3 { set; get; }
private int FinalExam { set; get; }
}
You don't need to create a new StudentForm each time you add a Student. Instead, you can have one StudentForm and use ShowDialog() when navigating to the Addition Screen, this you go back to the same instance of StudentForm.
Try removing the Class Student instantiation out of the event - btnSubmit_Click event
Student std = new Student();
I have been working on a program that requires two class definitions (clsCustomer and clsOrder) and a driver that is used for simulating an order form that calculates totals and prints a mailing label. The instructor provided partial code and I got rid of the previous errors that it had, but when I run the program and enter the information (name, address, quantity, price, etc.) only a "." shows up as the mailing label and both the extension and total price appear as "0.00". I tried playing with it and cannot seem to fix the issue. Here is the code:
namespace CS8
{
public partial class frmCS8 : Form
{
public frmCS8()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string strMailingLabel;
try
{
//Create an instance of clsCustomer using the overloaded constructor
clsCustomer cobjCustomer = new clsCustomer(txtName.Text, txtStreet.Text,
txtCity.Text, txtState.Text, txtZip.Text);
//Build mailing label using the Get methods for Customer.
strMailingLabel = cobjCustomer.Name + "\n" +
cobjCustomer.Street + "\n" +
cobjCustomer.City + ", " +
cobjCustomer.State + " " + cobjCustomer.Zip;
//Display mailing address
lblMailingLabel.Text = strMailingLabel;
//Create an instance of clsOrder using the overloaded constructor
clsOrder cobjOrder = new clsOrder
(txtDescription.Text,
int.Parse(txtQuantity.Text),
decimal.Parse(txtPrice.Text));
//Test the calculate Extended Price method
cobjOrder.calcExtendedPrice();
//Update the totals in shared variables.
cobjOrder.accumulateTotals();
//Test the Get property method of extended priced
lblExtension.Text = cobjOrder.ExtendedPrice.ToString("C");
//Shared properties are accessed using class name
//Test the Get Property methods of ReadOnly Shared properties
lblTotalCount.Text = clsOrder.TotalCount.ToString("N0");
lblTotalPrice.Text = clsOrder.TotalPrice.ToString("C");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message
+ "\n" + ex.StackTrace,
"Try/Catch - Unexpected Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}//end try
}
private void btnNextItem_Click(object sender, EventArgs e)
{
//clear the item fields
txtDescription.Clear();
txtQuantity.Clear();
txtPrice.Clear();
lblExtension.Text = "";
txtDescription.Focus();
}
private void btnResetSummary_Click(object sender, EventArgs e)
{
//Reset totals using the class name to access the shared method
clsOrder.resetTotals();
lblTotalPrice.Text = "";
lblTotalCount.Text = "";
lblMailingLabel.Text = "";
//Clear the rest of the form using next item method
btnNextItem_Click(sender, e);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
namespace CS8
{
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder()
{
}
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
//declare property methods
{
this.Description = cstrDescription;
this.Quantity = cintQuantity;
this.Price = cdecPrice;
}
//declare read-only properties
public decimal ExtendedPrice
{
get
{
return cdecExtendedPrice;
}
set
{
cdecExtendedPrice = value;
}
}
public string Description
{
get
{
return cstrDescription;
}
set
{
cstrDescription = value;
}
}
public int Quantity
{
get
{
return cintQuantity;
}
set
{
cintQuantity = value;
}
}
public decimal Price
{
get
{
return cdecPrice;
}
set
{
cdecPrice = value;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
set
{
cintTotalCount = value;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
namespace CS8
{
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public clsCustomer()
{
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstrZip = value;
}
}
}
}
Any assistance would be very much appreciated...
Use parameters, not class fields:
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
{
this.Description = strDescription;
this.Quantity = intQuantity;
this.Price = decPrice;
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = strName;
this.Street = strStreet;
this.City = strCity;
this.State = strState;
this.Zip = strZip;
}
I have a property Grid as follows:
I want to copy the complete content of the property grid to a data grid view(dataGeriView1) when submit button is clicked.
How to do this?
Please help.
private void Submit_Click(object sender, EventArgs e)
{
//propertyGrid1.SelectedObject = this;
dataGridView1.Columns.Add("Property", "Property");
dataGridView1.Columns.Add("Value", "Value");
GridItem gi = propertyGrid1.SelectedGridItem;
while (gi.Parent != null)
gi = gi.Parent;
foreach (GridItem item in gi.GridItems)
ParseGridItems(item); //recursive
dataGridView1.Sort(dataGridView1.Columns["Property"], ListSortDirection.Ascending);
}
private void ParseGridItems(GridItem gi)
{
if (gi.GridItemType == GridItemType.Category)
foreach (GridItem item in gi.GridItems)
ParseGridItems(item);
dataGridView1.Rows.Add(gi.Label, gi.Value);
}
Adapted from https://stackoverflow.com/a/12109186/1163434
Below is a sample snippet i have created to solve the above issue. Create a DataGridview by adding Columns Name,Age,Email,Phone.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Student std = new Student {Name = "Vimal" , Phone = "PhoneValue", Email="mymail",Age=24};
propertyGrid1.SelectedObject= std;
}
private void button1_Click(object sender, EventArgs e)
{
int index = dataGridView1.Rows.Count - 1;
Student std = (Student)propertyGrid1.SelectedObject;
dataGridView1.Rows[index].Cells["Name"].Value = std.Name;
dataGridView1.Rows[index].Cells["Age"].Value = std.Age;
dataGridView1.Rows[index].Cells["Email"].Value = std.Email;
dataGridView1.Rows[index].Cells["Phone"].Value = std.Phone;
}
}
public class Student
{
public int Age { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
I have to use a ListBox for this.
I currently know how to remove from a ListBox using this code:
private void removeButton_Click(object sender, EventArgs e)
{
REMOVE();
}
private void REMOVE()
{
int c = lstCart.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (lstCart.GetSelected(i))
{
lstCart.Items.RemoveAt(i);
}
}
}
But what I have found is that when I add another item, it clears the ListBox and shows each item from the list, so it includes the 'removed' item because it wasn't removed from the list, only the ListBox.
I'm thinking that what I need to do is remove the selected line from the List, then clear the ListBox and repopulate it with the updated List data. But I'm struggling to find out how to do this.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
OrderItem currentItem = new OrderItem(txtItemName.Text,
Decimal.Parse(txtPrice.Text), (int)numQTY.Value);
myBasket.Add(currentItem);
lstCart.Items.Clear();
foreach (OrderItem i in myBasket)
{
lstCart.Items.Add(String.Format("{0,-40}
{1,-40} {2,-40} {3,-40}", i.ProductName,
i.Quantity.ToString(), i.LatestPrice.ToString(),
i.TotalOrder.ToString()));
}
txtItemTotal.Text = "£" + myBasket.BasketTotal.ToString();
txtItemCount.Text = myBasket.Count.ToString();
}
private void removeButton_Click(object sender, EventArgs e)
{
int c = lstCart.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (lstCart.GetSelected(i))
{
lstCart.Items.RemoveAt(i);
}
}
????
}
}
ShoppingBasket class:
public class ShoppingBasket
{
public ShoppingBasket()
{
}
public new void Add(OrderItem i)
{
base.Add(i);
calcBasketTotal();
}
private void calcBasketTotal()
{
BasketTotal = 0.0M;
foreach (OrderItem i in this)
{
BasketTotal += i.TotalOrder;
}
}
public new void Remove(OrderItem i)
{
????
}
}
OrderItem class:
public class OrderItem
{
public OrderItem(string productName,
decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
Your add method calls Add() on a base class. Do you have a remove on your base class? If so, use that. Otherwise change your ShoppingBasket class to be:
The Orders list stores your OrderItems. Add and Remove from this list.
public class ShoppingBasket
{
public List<OrderItem> Orders { get; set; }
public ShoppingBasket()
{
Orders = new List<OrderItem>();
}
public void Add(OrderItem orderItem)
{
Orders.Add(orderItem);
}
public void Remove(OrderItem orderItem)
{
Orders.Remove(orderItem);
}
}
Usage:
var basket = new ShoppingBasket();
basket.Add( new OrderItem { OrderItemId = 1, ... } );
// Remove an OrderItem
basket.Remove( new OrderItem { OrderItemId = 1 } );