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);
}
}
Related
I need to split values from two columns into a datagridview.
You can see a screenshot of my values here:
I need to split match and result columns to have a column for every value.
This is my code:
Class:
using System;
using System.Collections.Generic;
namespace bexscraping
{
public class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}
form1:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace bexscraping
{
public partial class Form1 : Form
{
private List<Bet> Bets;
private Bet SelectedBet { get; set; }
public Form1()
{
InitializeComponent();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) {
SelectedBet = (Bet)dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0) {
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void LoadInfo()
{
string url = "http://www.betexplorer.com/soccer/australia/northern-nsw/results/";
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (HtmlNode row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
Bet rowBet = new Bet();
foreach (HtmlNode node in row.ChildNodes)
{
string data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains(("first-cell")))
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split("-", StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
if (node.GetAttributeValue("class", "").Contains(("result")))
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(":", StringSplitOptions.RemoveEmptyEntries);
rowBet.HomePoints = int.Parse(matchPoints[0];
rowBet.HostPoints = int.Parse(matchPoints[1];
if (node.GetAttributeValue("class", "").Contains(("last-cell")))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
}
}
}
I hope you can help me. Thanks!
Ok after I try it this is working solution for me.
Probably its diferent namespace but all components have same name.
Form1 class
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace Test
{
public partial class Form1 : Form
{
private List<Bet> Bets;
public Form1()
{
InitializeComponent();
Form1_Load_1();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private Bet SelectedBet { get; set; }
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
SelectedBet = (Bet) dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
private void LoadInfo()
{
var url = "http://www.betexplorer.com/soccer/australia/northern-nsw/results/";
var web = new HtmlWeb();
var doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (var row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
var rowBet = new Bet();
foreach (var node in row.ChildNodes)
{
var data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains("first-cell"))
{
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
}
if (node.GetAttributeValue("class", "").Contains("result"))
{
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
int help;
if (int.TryParse(matchPoints[0], out help))
{
rowBet.HomePoints = help;
}
if (matchPoints.Length == 2 && int.TryParse(matchPoints[1], out help))
{
rowBet.HostPoints = help;
}
}
if (node.GetAttributeValue("class", "").Contains("last-cell"))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
}
private void Form1_Load_1()
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
}
}
Bets class
using System;
using System.Collections.Generic;
namespace Test
{
class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public string Home { get; set; }
public string Host { get; set; }
public int HomePoints { get; set; }
public int HostPoints { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}
im doing a windows form application to open and load a database. the code needs to show single record view of the records and the listView view however i am stuck on the listVIew part.
here is the following code
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADOX;
namespace Ex3
{
public partial class changeButton : Form
{
public List<Client> ClientRecords = new List<Client>(); //Creates a list for the records to be stored
public string filename;
public string fileDir;
public string rec;
public bool checkBC;
public bool checkLC;
public string dataBaseFile;
public OleDbConnection conn;
public changeButton()
{
InitializeComponent();
}
int position = 0;
private void Form1_Load(object sender, EventArgs e)
{
credBalBox.Maximum = 9999999999;
savingBalBox.Maximum = 9999999999;
}
private void ConnectToDataBase()
{
try
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
dataBaseFile + ";";
conn = new OleDbConnection(strConn);
conn.Open();
}
catch (OleDbException e)
{
MessageBox.Show("Failed to connect to database: " + e.Message);
}
}
private void nextButton_Click(object sender, EventArgs e)
{
if (position < ClientRecords.Count - 1)
{
position++;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
private void previousButton_Click(object sender, EventArgs e)
{
if (position > 0)
{
position--;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
public void Print()
{
int positionAdd1;
positionAdd1 = position;
positionAdd1++;
currentRecLab.Text = positionAdd1.ToString();
MaxRecLab.Text = ClientRecords.Count.ToString();
if (position >= 0 && position < ClientRecords.Count)
{
nameBox.Text = ClientRecords[position].Name;
suburbBox.Text = ClientRecords[position].Suburb;
postBox.Text = ClientRecords[position].Postcode;
credBalBox.Text = ClientRecords[position].CreditBal.ToString();
savingBalBox.Text = ClientRecords[position].SavingBal.ToString();
}
else
{
nameBox.Text = "";
suburbBox.Text = "";
postBox.Text = "";
credBalBox.Text = "";
savingBalBox.Text = "";
}
}
private void addButton_Click(object sender, EventArgs e)
{
string sameAddName = "null";
string addName;
string addSuburb;
string addPostcode;
decimal addCredBal;
decimal addSavBal;
addName = nameBox.Text;
addSuburb = suburbBox.Text;
addPostcode = postBox.Text;
addCredBal = decimal.Parse(credBalBox.Text);
addSavBal = decimal.Parse(savingBalBox.Text);
string sqlPrefix = "INSERT INTO Client VALUES ";
string data = "(" + "'" + addName + "','" + addSuburb + "','" + addPostcode + "','" + addCredBal + "','" + addSavBal + "'" + ")";
string sql = sqlPrefix + data;
foreach (Client client in ClientRecords)
{
if (addName == client.Name)
{
sameAddName = "Name is not unique. Please use a unique name";
}
}
if (sameAddName == "null" && addSuburb != null)
{
ClientRecords.Add(new Client(addName, addSuburb, addPostcode, addCredBal, addSavBal));
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
int positions = ClientRecords.Count;
currentRecLab.Text = positions.ToString();
MaxRecLab.Text = positions.ToString();
nameBox.Text = addName;
suburbBox.Text = addSuburb;
postBox.Text = addPostcode;
credBalBox.Text = addCredBal.ToString();
savingBalBox.Text = addSavBal.ToString();
position = ClientRecords.Count - 1;
}
else
{
if ((sameAddName != "null") && (addSuburb == "") && (addPostcode == ""))
{
MessageBox.Show(sameAddName + "\nAlso, one of the fields are empty. Please fill it in before adding a new record");
}
else if (sameAddName != "null")
{
MessageBox.Show(sameAddName);
}
}
}
private void removeButton_Click(object sender, EventArgs e)
{
int recPosition = int.Parse(currentRecLab.Text);
recPosition = recPosition - 1;
position = 0;
ClientRecords.Remove(ClientRecords[recPosition]);
Print();
if (MaxRecLab.Text == "0")
{
currentRecLab.Text = "0";
}
}
private void loadButton_Click_1(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand ("SELECT * FROM Client", conn);
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Client nClient = new Client(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), decimal.Parse(rdr[3].ToString()), decimal.Parse(rdr[4].ToString()));
ClientRecords.Add(nClient);
Print();
}
}
}
private void connectButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select DataBase";
if (dialog.ShowDialog() == DialogResult.OK)
{
dataBaseFile = dialog.FileName;
DatabaseNameBox.Text = dataBaseFile;
ConnectToDataBase();
}
}
private void DatabaseNameBox_TextChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void nameBox_TextChanged(object sender, EventArgs e)
{
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
public class Client
{
protected string name;
protected string suburb;
protected string postcode;
protected decimal creditBal;
protected decimal savingBal;
public Client(string name, string suburb, string postcode, decimal creditBal, decimal savingBal)
{
this.name = name;
this.suburb = suburb;
this.postcode = postcode;
this.creditBal = creditBal;
this.savingBal = savingBal;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Suburb
{
get
{
return suburb;
}
set
{
suburb = value;
}
}
public string Postcode
{
get
{
return postcode;
}
set
{
postcode = value;
}
}
public decimal CreditBal
{
get
{
return creditBal;
}
set
{
creditBal = value;
}
}
public decimal SavingBal
{
get
{
return savingBal;
}
set
{
savingBal = value;
}
}
}
}
thanks in advance
further info
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
i want to be able to put the code here and when i click the load button from above it should load the listview
To load a listview I would use the following function - it uses a array of string and listviewitem do add items to a listview.
private void LoadListview()
{
string NAME = "John DOE";
string AGE = "30";
string SEX = "MALE";
string DOB = "08/28/1988";
string[] rowa = { NAME, AGE, SEX, DOB };
var listViewItema = new ListViewItem(rowa);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
}
You can find a step by step detail answer on my website: http://softvernow.com/2018/05/01/create-list-of-objects-and-load-listview-using-c/
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;
The following link is the request:
http://www.discountbox.in/OrkutJSONServlet?locality=Amravati®ion=Maharashtra&maxOffers=12&offerRequestType=PromotedOffersRequest&category=All
The following is the code for main page where I m trying to display the string which is stored in the variable named 'feed':
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace PhoneApp20
{
public class Transaction
{
public string id, offer, image;
public String ID { get; set; }
public String Offer { get; set; }
public String Image { get; set; }
public Transaction(String id, String offer, String image)
{
this.id = id;
this.offer = offer;
this.image = image;
}
}
public partial class MainPage : PhoneApplicationPage
{
String soffer, sid, simage;
String Offerid = "20";
int i1, j1, k1;
// Constructor
Transaction t;
public static String message = "Hello";
public MainPage()
{
InitializeComponent();
this.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
HttpWebRequest request = HttpWebRequest.CreateHttp("http://www.discountbox.in/OrkutJSONServlet?locality=Amravati®ion=Maharashtra&maxOffers=12&offerRequestType=PromotedOffersRequest&category=All");
request.BeginGetResponse(new AsyncCallback(HandleResponse), request);
}
public void HandleResponse(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
using (WebResponse response = request.EndGetResponse(result))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string feed = reader.ReadToEnd();
Parse(feed);
}
}
}
}
private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
}
private void init()
{
TextBox tx = new TextBox();
}
private void Parse(string feed)
{
string data1 = feed;
string[] tokens;
string[] id, image, offer;
string str;
char[] sep = { ',' };
int x, y;
x = feed.IndexOf("[");
y = feed.IndexOf("]");
str = feed.Substring(x + 1, y - x - 1);
tokens = str.Split(sep);
id = new string[tokens.Length];
offer = new string[tokens.Length];
image = new string[tokens.Length];
string[] tt = new String[tokens.Length];
int j = 0;
for (int i = 0; i < tokens.Length; i++)
{
tt[j] = tokens[i].Substring(1, tokens[i].Length - 2);
j++;
}
i1 = 0; j1 = 1; k1 = 2;
int m = 0;
int maxcount = tt.Length;
for (int i = 0; i < maxcount / 3; i++)
{
if (i >= tt.Length)
break;
id[m] = tt[i1];
id[m] = id[m].Replace("\"", "");
image[m] = tt[j1];
image[m] = image[m].Replace("\"", "");
image[m] = image[m].Replace("\\/\\/", "\\\\");
image[m] = image[m].Replace("\\/", "\\\\");
offer[m] = tt[k1];
offer[m] = offer[m].Replace("\"", "");
i1 += 3;
j1 += 3;
k1 += 3;
m++;
}
soffer = offer[0];
sid = id[0];
simage = image[0];
t = new Transaction(sid, soffer, simage);
//for (i1 = 0; i1 < maxcount / 3; i1++)
//{
// Console.WriteLine("Id = {0} ", id[i1]);
// Console.WriteLine("Offer = {0} ", offer[i1]);
// Console.WriteLine("Image = {0} ", image[i1]);
//}
//Console.ReadLine();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
}
private void button2_Click(object sender, RoutedEventArgs e)
{
}
private void button3_Click(object sender, RoutedEventArgs e)
{
}
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
Now, I have tried every controls available to display the string, but it doesn't display anything on the emulator.
To display a string on the screen, the simplest method is to have a TextBlock on the page and update it's Text property.
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.