I am having some issues with listbox, have been trying to make it so that when I click on an item it will populate textboxes(picture below) with information from that item.
http://i.stack.imgur.com/G32uq.jpg (wont let me post pictures).
Heres my code (This code I have currently will populate the text boxes with what I need, but I want it to be able to do the same by clicking the items).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int index;
private const int SIZE = 4;
private int count = 0;
private Employee[] employees = new Employee[SIZE];
List<Employee> listEmp = new List<Employee>(SIZE);
public Form1()
{
InitializeComponent();
listEmp.Add(new Hourly(1, "Karl", "lane drive", "201-9090", 40, 12.00)); //item1
listEmp.Add(new Salaried(2, "Steve", "circle road", "803-1230", 1200)); // item2
listEmp.Add(new Hourly(3, "Westley", "square alley", "892-2000", 40, 10.00)); //item3
listEmp.Add(new Salaried(4, "Anders", "triangle boulevard", "910-8765", 1000)); //item4
index = 0;
computPayBtn.Enabled = true;
listBox1.DataSource = listEmp;
}
// opens a file and reads data into the employee objects
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
Stream myStream = null;
Employee tempEmploy = null;
string type = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "text files (*.txt)|*txt";
count = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
StreamReader data = new StreamReader(myStream);
do
{
type = data.ReadLine();
if (type != null)
{
if (type == "hourly")
tempEmploy = new Hourly();
else if (type == "salaried")
tempEmploy = new Salaried();
tempEmploy.ReadData(data);
employees[count++] = tempEmploy;
}
} while (type != null);
computPayBtn.Enabled = true;
count = 0;
}
}
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
// shows next employee when clicked.
private void computPayBtn_Click_1(object sender, EventArgs e)
{
checkbox.Clear( );
int index = count;
if (index < SIZE)
{
string emp = "Fluffshuffle Electronics check no. ";
emp += string.Format("{0}", index);
emp += Environment.NewLine;
emp += Environment.NewLine;
emp += " Pay to the order of ";
emp += employees[index].Name;
emp += Environment.NewLine;
emp += " ";
emp += string.Format("{0:C}", employees[index].CalcPay());
emp += Environment.NewLine;
emp += Environment.NewLine;
emp += " First National Bank";
checkbox.Text = emp;
namebox.Text = employees[index].Name;
addressbox.Text = employees[index].Address;
phonebox.Text = employees[index].PhoneNum;
empNumbox.Text = string.Format("{0}", employees[index].EmpNum);
Hourly houremploy = employees[index] as Hourly;
if (houremploy != null)
{
hoursbox.Text = string.Format("{0:F2}", houremploy.HoursWorked);
wagebox.Text = string.Format("{0:F2}", houremploy.HourlyWage);
salarybox.Clear();
}
Salaried salemploy = employees[index] as Salaried;
if (salemploy != null)
{
hoursbox.Clear();
wagebox.Clear();
salarybox.Text = string.Format("{0:F2}", salemploy.Salary);
}
count++;
}
else
{
computPayBtn.Enabled = false;
namebox.Clear( );
addressbox.Clear(); ;
phonebox.Clear(); ;
empNumbox.Clear( );
hoursbox.Clear();
wagebox.Clear();
salarybox.Clear();
count = 0;
}
}
// saves employee objects into a txt file.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream = null;
count = SIZE;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = "c:\\";
saveFileDialog.Filter = "text files (*.txt)|*txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog.OpenFile()) != null)
{
StreamWriter data = new StreamWriter(myStream);
for (int i = 0; i < count; i++)
{
employees[i].WriteData(data);
employees[i] = null;
}
data.Close();
computPayBtn.Enabled = false;
count = 0;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
And the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
// provides methods to read and write objects to a file
public interface IStorable
{
// writes object's data to a StreamWriter object
// The StreamReader object to write to
void WriteData(StreamWriter swo);
// reads object's data from a StreamReader object
// The StreamReader object to read from
void ReadData(StreamReader sro);
}
public abstract class Employee : IStorable
{
private int empNum;
private string name;
private string address;
private string phoneNum;
protected const double STATE_TAX = 0.075;
protected const double FED_TAX = 0.20;
// set data members to defaults
public Employee()
{
empNum = 0;
name = "unknown";
address = "unknown";
phoneNum = "unknown";
}
// set data members to values passed to method
// employee number, name, address, and phone number
public Employee(int _empNum, string _name, string _address, string _phoneNum)
{
empNum = _empNum;
name = _name;
address = _address;
phoneNum = _phoneNum;
}
public int EmpNum
{
get { return empNum; }
set { empNum = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string PhoneNum
{
get { return phoneNum; }
set { phoneNum = value; }
}
// reads object's data from a StreamReader object
// The method is virtual so we can use polymorphism
public virtual void ReadData(StreamReader sro)
{
EmpNum = int.Parse(sro.ReadLine());
Name = sro.ReadLine();
Address = sro.ReadLine();
PhoneNum = sro.ReadLine();
}
// writes object's data to a StreamReader object
// The method is virtual so we can use polymorphism
public virtual void WriteData(StreamWriter sro)
{
sro.WriteLine(this.EmpNum);
sro.WriteLine(this.Name);
sro.WriteLine(this.Address);
sro.WriteLine(this.PhoneNum);
}
// calculates the employee's net pay
public abstract double CalcPay();
}
// The Hourly Class - represents an hourly employee
// Inherits from Employee
class Hourly : Employee
{
private const int WEEK = 40;
private const double BONUS = 1.5;
private double hoursWorked;
private double hourlyWage;
//set data members to defaults
public Hourly()
{
hoursWorked = 0.0;
hourlyWage = 0.0;
}
// set data members to values passed as arguments
// employee number, name, address, phone number, hours, and wage
public Hourly(int _empNum, string _name, string _address, string _phoneNum, double _hours, double _wage)
: base(_empNum, _name, _address, _phoneNum)
{
hoursWorked = _hours;
hourlyWage = _wage;
}
public double HoursWorked
{
get { return hoursWorked; }
set { hoursWorked = value; }
}
public double HourlyWage
{
get { return hourlyWage; }
set { hourlyWage = value; }
}
// calculates gross pay
// hours * wage + time and 1/2 for overtime
public override double CalcPay()
{
double overTime = 0.0;
if (hoursWorked > WEEK)
{
overTime = hoursWorked - WEEK;
hoursWorked -= WEEK;
}
double grossPay = hoursWorked * hourlyWage + overTime * hourlyWage * BONUS;
double stateTax = grossPay * STATE_TAX;
double fedTax = grossPay * FED_TAX;
return (grossPay - stateTax - fedTax);
}
// reads object's data from a StreamReader object
// Over-rides the ReadData method in Employee
public override void ReadData(StreamReader sro)
{
HoursWorked = double.Parse(sro.ReadLine());
HourlyWage = double.Parse(sro.ReadLine());
base.ReadData(sro);
}
// writes object's data to a StreamWriter object
// Over-rides the WriteData method in Employee
public override void WriteData(StreamWriter swo)
{
swo.WriteLine("hourly");
swo.WriteLine(this.HoursWorked);
swo.WriteLine(this.HourlyWage);
base.WriteData(swo);
}
}
class Salaried : Employee
{
private const double BENEFITS = 0.0524;
private double salary;
// set data members to defaults
public Salaried()
{
salary = 0.0;
}
// set data members to values passed as arguments
// employee number, name, address, phone number, salary
public Salaried(int _empNum, string _name, string _address, string _phoneNum, double _salary)
: base(_empNum, _name, _address, _phoneNum)
{
salary = _salary;
}
public double Salary
{
get { return salary; }
set { salary = value; }
}
// calculates pay for a salaried employee
public override double CalcPay()
{
double stateTax = salary * STATE_TAX;
double fedTax = salary * FED_TAX;
double bennies = salary * BENEFITS;
return (salary - stateTax - fedTax - bennies);
}
//reads object's data from a StreamReader object
public override void ReadData(StreamReader sro)
{
Salary = double.Parse(sro.ReadLine());
base.ReadData(sro); // call Employee's ReadData to get name, address, etc
}
// writes data to StreamWriter
public override void WriteData(StreamWriter swo)
{
swo.WriteLine("salaried");
swo.WriteLine(this.Salary);
base.WriteData(swo);
}
}
}
Thanks in advance for any help.
Use listbox's click event; Cast the SelectedItems[0] as employee and populate the textboxes. Set multiple selection of the listbox to false for simplicity. eg:
private void listBox1_Clik(object sender, EventArgs e)
{
Employee employee = listBox1.SelectedItems[0] as Employee;
if (employee != null)
{
// use the employee object to populate the textbox.
}
}
Take a look at the SelectedIndexChanged event on ListBox, it might do what you want. In fact the sample code in the docuemntation shows how to select an item in a second ListBox when an item is selected in the first ListBox so that should give you some idea.
Related
Im having a problem in my listview because whenever I get value in other form it is not adding on the list but when I put breakpoint it have a value but still not adding on my listview.
here is my function in form1 getting values from datagridview
public void dataGridView1_DoubleClick(object sender, EventArgs e)
{
qtyOfOrders orders = new qtyOfOrders();
if (dataGridView1.SelectedRows.Count > 0)
{
String mealname = dataGridView1.SelectedRows[0].Cells[1].Value + String.Empty;
String price1 = dataGridView1.SelectedRows[0].Cells[2].Value + String.Empty;
pts.meal = mealname;
pts.qtyprice = Int32.Parse(price1);
orders.Show();
}
}
here is my function from form2 and will save data in listview in form1
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
c.listView1.Items.Add(pts.meal);
c.qtyOrder.ListView.Items[0].SubItems.Add(pts.qtynumber.ToString());
c.price111.ListView.Items[0].SubItems.Add(pts.TotalPrice.ToString());
this.Hide();
}
this is my class
namespace jollibee4
{
class pricetempstorage
{
static int qtyNumber;
static int qtyPrice;
static int ListViewCount;
static String Meal;
static int totalprice;
public int TotalPrice
{
get
{
return totalprice;
}
set
{
totalprice = qtyNumber * qtyPrice;
}
}
public int qtynumber
{
get
{
return qtyNumber;
}
set
{
qtyNumber = value;
}
}
public int qtyprice
{
get
{
return qtyPrice;
}
set
{
qtyPrice = value;
}
}
public int listviewCount
{
get
{
return ListViewCount;
}
set
{
ListViewCount = value;
}
}
public String meal
{
get
{
return Meal;
}
set
{
Meal = value;
}
}
}
}
Try adding this code this.listView1.View = View.Details; After the c.listView1.Items.Add(pts.meal);
form1
public List<pricetempstorage> Items { get; private set; }
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
Items.Add(pts);
this.Hide();
}
Create a shopping cart class where items can be append in list
I assume pricetempstorage is your class of item, its name can be product
public static ShoppingCart GetInstance()
{
if (cart == null)
{
cart = new ShoppingCart();
}
return cart;
}
protected ShoppingCart()
{
Items = new List<pricetempstorage>();
}
You have many architectural and stylistic issues with your program (use of static, capitalization, etc.)--to correct them all would require a very lengthy response.
Your code isn't working because you're creating a new instance of the cashier class, and then you're updating its listView1 object. What I think you're trying to do is update the listView object of Form2. So what you should be doing is grabbing a reference to Form2 and populating its ListView object in your OK_Click event handler...
Just a tip here: Public properties should have an initial capital letter. Your pricetempstorage class needs some work.
how to update e specific value on a list..
for example when i click a button it adds the product on the list
name: coffe || quantity:1 || Price:2$
and when i click angain the same product the quantity increases by 1
i used this code but it doesnt change the number of the quantity.
private BindingList<recipt> Lista2 = new BindingList<recipt>();
private void addtolist(object sender, EventArgs e)
{
Button b = (Button)sender;
Product p = (Product)b.Tag;
recipt fat = new recipt ()
{
Name= p.Name,
quantity= 1,
price = p.Cmimi
};
bool found = false;
if (listBox1.Items.Count > 0)
{
foreach (var pr in Lista2)
{
if (pr.Name== p.Name)
{
pr.quantity= pr.quantity+ 1;
found = true;
}
}
if (!found)
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
}
else
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
pe.Faturs.Add(fat);
pe.SaveChanges();
Total = Total + (int)fat.price;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
For updating values in ListBox automatically you need set BindingList of receipts to the ListBox.DataSource and make Receipt class implement INotifyPropertyChanged
public class Receipt : INotifyPropertyChanged
{
public string Name { get; }
public int Quantity { get; private set; }
public decimal Price { get; }
public string BillNumber { get; private set; }
public decimal Total => Price * Quantity;
public string Info => $"{nameof(Name)}: {Name} || {nameof(Quantity)}: {Quantity} || {nameof(Price)}: {Price:C} || {nameof(Total)}: {Total:C}";
public Receipt(string name, decimal price, string billNumber)
{
Name = name;
Price = price;
BillNumber = billNumber;
Quantity = 1;
}
public void AddOne()
{
Quantity += 1;
RaisePropertyChanged(nameof(Info));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Then in the form
public class YourForm : Form
{
private readonly BindingList<Receipt> _Receipts;
public YourForm()
{
_Receipts = new BindingList<Receipt>();
listBox1.DisplayMember = "Info";
listBox1.DataSource = _Receipts;
}
private void AddToList(object sender, EventArgs e)
{
var button = (Button) sender;
var product = (Product) button.Tag;
var receiptInfo = _Receipts.FirstOrDefault(receipt => receipt.Name.Equals(product.Name));
if (receiptInfo == null)
{
receiptInfo = new Receipt(product.Name, product.Cmimi, txtNrbill.Text);
_Receipts.Add(receiptInfo);
}
else
{
receiptInfo.AddOne();
}
}
}
I have a text file call groceries. That contain text similar to the following:
regular,cereal,4.00,1;
fresh,rump steak,11.99,0.8;
The code below is trying to read the text file, split the string and then write to a text file called invoice.
The invoice text file should read read line in the groceries file, list whether it is a "fresh" or "regular" grocery item. If fresh GST is not applied if regular GST is applied. Calculate the cost on weight for fresh and quantity for regular and then display a total cost of items listed.
Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines ("Groceries.txt");
File.WriteAllLines("Invoice.txt", invoices.ToArray());
List<string> invoices = new List<string>();
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "fresh";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "regular";
grocery.Price = 50;
grocery.Quantity = 2;
double price = price.Calculate();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
invoices.Add(counter + "," + grocery + price+Quantity+"," + DateTime.Now.Date);
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
try something like that
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines("Groceries.txt");
List<string> invoices = new List<string>();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
var list = grocery2.Split(',');
if (list[0].Equals("fresh"))
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = list[1];
freshGrocery.Price = double.Parse(list[2]);
freshGrocery.Weight = double.Parse(list[3].Replace(";", ""));
invoices.Add(counter + "," + freshGrocery.Name + "," + freshGrocery.Price + "," + freshGrocery.Weight + "," + DateTime.Now.Date);
}
else if (list[0].Equals("regular"))
{
Grocery grocery = new Grocery();
grocery.Name = list[1];
grocery.Price = double.Parse(list[2]);
grocery.Quantity = int.Parse(list[3].Replace(";", ""));
double price = grocery.Calculate();
invoices.Add(counter + "," + grocery.Name + "," + price + "," + grocery.Quantity + "," + DateTime.Now.Date);
}
}
File.WriteAllLines("Invoice.txt", invoices.ToArray());
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
}
My question is how can I find employee by his ID for example if I type in textbox 17432 and when I click on search button its should give me employee id fullname lastname and salary information .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
Employee[] employee = new Employee[10];
public Form1()
{
InitializeComponent();
employee[0] = new Employee(17432, "john", "Adverd", 800.00);
employee[1] = new Employee(17433, "Adrian", "Smith", 800.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 17000.00);
}
private void Searchbtn_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
for (int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
listBox1.Items.Add(employeeString);
}
}
public void Lowestemployeesalary()
{
listBox1.Items.Clear();
double Minimumsal = employee[0].Salary;
for(int i = 0; i < employee.Count(); i++)
{
if(Minimumsal > employee[i].Salary )
{
Minimumsal = employee[i].Salary;
}
}
for(int j = 0; j < employee.Count(); j++)
{
if(Minimumsal == employee[j].Salary)
{
string result = string.Format("{0} {1} {2} {3}", employee[j].EmployeeIDNum, employee[j].FullName, employee[j].LastName, employee[j].Salary);
listBox1.Items.Add(result);
}
}
}
public void Highemployeesalary()
{
listBox1.Items.Clear();
double Mixsal = employee[0].Salary;
for (int i = 0; i < employee.Count(); i++)
{
if (Mixsal < employee[i].Salary)
{
Mixsal = employee[i].Salary;
}
}
for (int j = 0; j < employee.Count(); j++)
{
if (Mixsal == employee[j].Salary)
{
string result = string.Format("{0} {1} {2} {3}", employee[j].EmployeeIDNum, employee[j].FullName, employee[j].LastName, employee[j].Salary);
listBox1.Items.Add(result);
}
}
}
private void getinfibtn_Click(object sender, EventArgs e)
{
Lowestemployeesalary();
}
private void highestbtn_Click(object sender, EventArgs e)
{
Highemployeesalary();
}
private void sreachbtn_Click(object sender, EventArgs e)
{
//// Need Some Thing Here
}
}
}
And Here is my Class Employee
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
You have collection of employee in your form.
You just need simple Linq to find an employee for given employeeid.
var found = employee.FirstOrDefault(e=>e.EmployeeIDNum == employeeid);
if(found != null)
{
// logic here.
// found.employeeInformationToString();
listBox1.Items.Clear(); // check this if you want to clear.
listBox1.Items.Add(found.employeeInformationToString());
}
So your complete search code should be something like...
private void sreachbtn_Click(object sender, EventArgs e)
{
//// Need Some Thing Here
int employeeid;
if(int.TryParse(textbo1.Text, out employeeid)) // use your textbox name.
{
var found = employee.FirstOrDefault(e=>e.EmployeeIDNum == employeeid);
if(found != null)
{
// logic here.
found.employeeInformationToString()
}
}
}
Update :
Looks like you are not familiar with Linq , in this case try uing traditional looping.
private void sreachbtn_Click(object sender, EventArgs e)
{
//// Need Some Thing Here
int employeeid;
if(int.TryParse(textbo1.Text, out employeeid))
{
Employee found= null;
foreach(var emp in employee)
{
if(emp.EmployeeIDNum == employeeid)
{
found = emp;
break;
}
}
//var found = employee.FirstOrDefault(e=>e.EmployeeIDNum == employeeid);
if(found != null)
{
// logic here.
found.employeeInformationToString()
}
}
}
Here you go..
private void sreachbtn_Click(object sender, EventArgs e)
{
int searchID = int.Parse(txtIdSearch.Text);
// Need to handle if the user input is not a number..
Employee[] employeeResults = employee.Where(e => e.employeeID == searchID).ToArray();
// For possibility that your ID is not unique..
// code to display results
for (int i = 0; i < employeeResults .Length; i++)
{
string employeeString = employeeResults [i].employeeInformationToString() + "\r\n";
listBox1.Items.Add(employeeString);
}
}
How would I go about changing to code to eliminate the textbox that takes the value of the seatnumber and makes the reservation they can simply select which seat they want from the seating chart in the listbox and click make reservation. I know there's some unused code in here that needs cleaned up just ignore it i've been playing around with different ways to do this.
Heres the form code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Reservations
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Flight curFlight;
List<Flight> flightlist = new List<Flight>();
Flight flight1 = new Flight("Cessna Citation X", "10:00AM", "Denver", 6, 2);
Flight flight2 = new Flight("Piper Mirage", "10:00PM", "Kansas City", 3, 2);
private void Form1_Load(object sender, EventArgs e)
{
MakeReservations();
DisplayFlights();
SetupFlights();
}
private void lstFlights_SelectedIndexChanged(object sender, EventArgs e)
{
curFlight = (Flight)lstFlights.SelectedItem;
txtDepart.Text = curFlight.DepartureTime;
txtDestination.Text = curFlight.Destination;
string[] seatChart = curFlight.SeatChart;
DisplaySeatChart(seatChart);
}
private void DisplaySeatChart(string[] seating)
{
lstSeatChart.Items.Clear();
for (int seat = 0; seat <= seating.GetUpperBound(0); seat++)
{
lstSeatChart.Items.Add("Seat: " + (seat + 1) + " " + seating[seat]);
}
}
private void SetupFlights()
{
//flightlist.Add(flight1);
//flightlist.Add(flight2);
}
private void MakeReservations()
{
flight1.MakeReservation("Dill", 12);
flight1.MakeReservation("Deenda", 3);
flight1.MakeReservation("Schmanda", 11);
flight2.MakeReservation("Dill", 4);
flight2.MakeReservation("Deenda", 2);
}
private void DisplayFlights()
{
lstFlights.Items.Clear();
lstFlights.Items.Add(flight1);
lstFlights.Items.Add(flight2);
}
private void btnMakeReservation_Click(object sender, EventArgs e)
{
string name;
int seatNum;
string[] seatChart = curFlight.SeatChart;
if (txtCustomerName.Text != "" && txtSeatNum.Text != "")
{
name = txtCustomerName.Text;
seatNum = Convert.ToInt16(txtSeatNum.Text);
curFlight.MakeReservation(name, seatNum);
lstSeatChart.Items.Clear();
DisplaySeatChart(seatChart);
}
else
{
MessageBox.Show("Please Fill out Name and Seat Number.", "Reservation Error");
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
string name;
int seatNum;
string[] seatChart = curFlight.SeatChart;
if (txtCustomerName.Text != "" && txtSeatNum.Text != "")
{
name = txtCustomerName.Text;
seatNum = Convert.ToInt16(txtSeatNum.Text);
curFlight.EditReservation(name, seatNum);
lstSeatChart.Items.Clear();
DisplaySeatChart(seatChart);
}
else
{
MessageBox.Show("Please Fill out Name and Seat Number.", "Reservation Error");
}
}
}
}
HERES THE CLASS CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Reservations
{
class Flight
{
private string mPlane;
private string mDepartureTime;
private string mDestination;
private int mRows;
private int mSeats;
private string[] mSeatChart;
public Flight()
{
}
public Flight(string planeType, string departureTime, string destination, int numRows, int numSeatsPerRow)
{
this.Plane = planeType;
this.DepartureTime = departureTime;
this.Destination = destination;
this.Rows = numRows;
this.Seats = numSeatsPerRow;
// create the seat chart array
mSeatChart = new string[Rows * Seats];
for (int seat = 0; seat <= mSeatChart.GetUpperBound(0); seat++)
{
mSeatChart[seat] = "Open";
}
}
public string Plane
{
get { return mPlane; }
set { mPlane = value; }
}
public string DepartureTime
{
get { return mDepartureTime; }
set { mDepartureTime = value; }
}
public string Destination
{
get { return mDestination; }
set { mDestination = value; }
}
public int Rows
{
get { return mRows; }
set { mRows = value; }
}
public int Seats
{
get { return mSeats; }
set { mSeats = value; }
}
public string[] SeatChart
{
get { return mSeatChart; }
set { mSeatChart = value; }
}
public override string ToString()
{
return this.Plane;
}
public void MakeReservation(string name, int seat)
{
if (IsFull(seat) == false)
{
if (seat <= (Rows * Seats) && mSeatChart[seat - 1] == "Open")
{
mSeatChart[seat - 1] = name;
}
else
{
MessageBox.Show("Seat is taken.", "Reservation Error");
}
}
else
{
MessageBox.Show("Plane is full please choose another flight.", "Reservation Error");
}
}
public void EditReservation(string name, int seat)
{
if (seat <= (Rows * Seats) && mSeatChart[seat - 1] != "Open")
{
mSeatChart[seat - 1] = name;
}
if (seat > mSeatChart.GetUpperBound(0))
{
MessageBox.Show("Invalid seat number.", "Reservation Error");
}
else
{
if (mSeatChart[seat - 1] == "Open")
{
MessageBox.Show("No such reservation exists.", "Reservation Error");
}
}
}
public bool IsFull(int seat)
{
if (seat >= (Rows * Seats) && mSeatChart[seat - 1] != "Open")
{
return true;
}
return false;
}
}
}
An item in your seat chart collection should first have an identifier. Once you have that, that identifier (or a description, name, etc.) All 'Open' seats should be added to a list box that the user can select. Upon reservation, you simply determine which list box items are selected. You can do this with or without data binding.
List<Seat> seats;
private void button6_Click(object sender, EventArgs e)
{
seats = new List<Seat>
{
new Seat { Identifier = "A1", Description = "A1 - Window" },
new Seat { Identifier = "A2", Description = "A2 - Center" },
new Seat { Identifier = "A3", Description = "A3 - Aisle" }
};
listBox1.DataSource = seats;
listBox1.DisplayMember = "Description";
listBox1.ValueMember = "Identifier";
}
private void button7_Click(object sender, EventArgs e)
{
// get selected seat
foreach (Seat selectedSeat in listBox1.SelectedItems)
{
MessageBox.Show(selectedSeat.Identifier);
}
}
Of course you can play around the example and display only those seats that are free. You can do that several ways, one of them is by adding a flag on your Seat class.
Answer is simple rather than
seatNum = Convert.ToInt16(txtSeatNum.Text);
use
seatNum = lst.SeatChart.SelectedIndex + 1;