C# how to load listview - c#

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/

Related

How to transfer values to DataGridView in another Form

I'm creating a shopping application for which I need to transfer my selected items (via add to cart button) to a DataGridView in another Form so that it can show all the items that I've bought. For this I have designed a global function in my second Form so that whenever I press the "add to cart"-button in my first Form the values are added in the DataGridView in the second Form. But the code is not showing anything in the DataGridView so far.
Form1:
public partial class CLOTHES : Form
{
public static int cost = 0;
public static string name = "";
public static string size = "";
public static string NAME = "";
public static string SIZE = "";
public static int total = 0;
public CLOTHES()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
if (comboBox1.SelectedIndex == 0)
{
SIZE = "small";
label1.Text = "T-SHIRT";
cost = 300;
}
else if (comboBox1.SelectedIndex == 1)
{
SIZE = "MEDIUM";
label1.Text = "T-SHIRT";
cost = 400;
}
else if (comboBox1.SelectedIndex == 2)
{
SIZE = "LARGE";
label1.Text = "T-SHIRT";
cost = 500;
}
name = label1.Text;
size = comboBox1.SelectedIndex.ToString();
cart.populatedatagridview(name, size, cost);
nextform(cost, size, name);
}
}
void nextform(int cost, string size, string name)
{
total = cost;
NAME = name;
size = SIZE;
MessageBox.Show("total " + total);
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
cart f5 = new cart();
f5.ShowDialog();
}
}
Form2:
public partial class cart : Form
{
public cart()
{
InitializeComponent();
}
public static void populatedatagridview(string name, string size, int total)
{
cart cs = new cart();
string[] row = { "" + name, "" + size, "" + total };
cs.dataGridView1.Rows.Add(row);
}
}
See code update below, just store your cart in variable, and pass to form2 function to bind your data to gridview before displaying form2
Form1:
public partial class CLOTHES : Form
{
public static int cost = 0;
public static string name = "";
public static string size = "";
public static string NAME = "";
public static string SIZE = "";
public static int total = 0;
List<string[]> data = new List<string[]>();
public CLOTHES()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
if (comboBox1.SelectedIndex == 0)
{
SIZE = "small";
label1.Text = "T-SHIRT";
cost = 300;
}
else if (comboBox1.SelectedIndex == 1)
{
SIZE = "MEDIUM";
label1.Text = "T-SHIRT";
cost = 400;
}
else if (comboBox1.SelectedIndex == 2)
{
SIZE = "LARGE";
label1.Text = "T-SHIRT";
cost = 500;
}
name = label1.Text;
size = comboBox1.SelectedIndex.ToString();
nextform(cost, size, name);
string[] row = { "" + name, "" + size, "" + total };
data.Add(row);
}
}
void nextform(int cost, string size, string name)
{
total = cost;
NAME = name;
size = SIZE;
MessageBox.Show("total " + total);
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
cart f5 = new cart();
f5.populatedatagridview(data);
f5.ShowDialog();
}
}
Form2:
public partial class cart : Form
{
public cart()
{
InitializeComponent();
}
public void populatedatagridview(List<string[]> data)
{
foreach (var item in data)
{
dataGridView1.Rows.Add(item);
}
}
}

C# Bringing the value twice error

public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
}
Hello so when we tried to carry a value from form1 > form2(label) > form3(textbox) with added this below it gives a error:
Error System.InvalidOperationException: The connectionString Property has not been initialized at System.Data.OleDbConnection.PermissionDemand .
Update:After adding that below, it shows this error enter image description here
public partial class MenClothing : Form
{
OleDbConnection connect = new OleDbConnection();
public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
}
public MenClothing()
{
InitializeComponent();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C: \Users\Teronkee\Desktop\OFFICAL STAC\OFFICAL STAC\StacProductions\DatabaseSaveItem.accdb";
}
private int upperCase(string pass)
{
int num = 0;
foreach (char ch in pass)
{
if (char.IsUpper(ch))
{
num++;
}
}
return num;
}
private void btnlogout_Click(object sender, EventArgs e)
{
this.Hide();
Form2 Return = new Form2(txtUsername.Text);
Return.ShowDialog();
}
private void MenClothing_Load(object sender, EventArgs e)
{
try
{
connect.Open();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ItemUrl.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ItemUrl.Text;
}
private void button1_Click(object sender, EventArgs e)
{
{
try
{
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "insert into RegisterItem([Name], [Url],[Description], [Price]) values('" + ItemName.Text + "','" + ItemUrl.Text + "','" + ItemDescription.Text + "','" + ItemPrice.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
connect.Close();
}
string str = ItemUrl.Text;
pictureBox1.ImageLocation = str;
//string str = textBox1.Text;
// Image img = Image.FromFile(str);
// pictureBox1.Image = img;
txtUsername = txtID1;
ItemName = txtName1;
ItemDescription = txtDescription1;
ItemPrice = txtPrice1;
ItemName.Text = "";
ItemDescription.Text = "";
ItemPrice.Text = "";
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtUsername.Text == txtID1.Text)
{
}
}
}
}
You are not setting the connection string in the constructor accepting a string.
Change it like so:
public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C: \Users\Teronkee\Desktop\OFFICAL STAC\OFFICAL STAC\StacProductions\DatabaseSaveItem.accdb";
}
or better, to avoid code duplication, move the line setting the connectionstring to its own function and call it from both constructors

Printing Class information C# Forms

I'm trying to make a program which stores a bunch of country information from a country class in an AVL tree. I am using a form which prints out the list of countries which is saved in a CSV file and when I click on a country I want the program to print out information which corresponds to the selected country.
The problem I am having is getting it to print out the GDP in a text box when I select a country in the list box.
What code can I put to into list box which will print the gdp into a textbox?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
.
namespace country
{
public partial class Form1 : Form
{
AVLTree<Country> myTree = new AVLTree<Country>();
List<Country> Countries = new List<Country>();
static string[] headers = new string[6];
string buffer = "";
public Form1()
{
InitializeComponent();
const int MAX_LINES_FILE = 50000;
string[] AllLines = new string[MAX_LINES_FILE];
AllLines = File.ReadAllLines("countries.CSV");
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
LinkedList<string> tradePartner = new LinkedList<string>();
string[] partners = columns[5].Split(';', '[', ']');
foreach (string x in partners)
{
if (x != "")
{
tradePartner.AddLast(x);
}
}
myTree.InsertItem(new Country(columns[0], float.Parse(columns[1]), float.Parse(columns[2]), float.Parse(columns[3]), float.Parse(columns[4]), tradePartner));
}
}
myTree.PreOrder(ref buffer);
Console.WriteLine("Tree Contains " + buffer);
Add();
}
private void Add()
{
myTree.CInOrder(ref Countries);
foreach (Country y in Countries)
{
listBox1.Items.Add(y.Countryname);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
country class
public Country (string cn, float gd, float i, float tb, float hd, LinkedList<string> mt)
{
this.Countryname = cn;
this.gdp = gd;
this.inflation = i;
this.tradeBalance = tb;
this.hdi = hd;
this.mtp = mt;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return Countryname.CompareTo(temp.Countryname);
}
public override string ToString()
{
foreach (string i in mtp)
x += i + ",";
return Countryname + " " + gdp + " " + inflation + " " + tradeBalance +" " + hdi + " " + x;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
if (country != null )
textBox1.Text = country.gdp;
}

Selecting and displaying certain items from list based on specific property

i have a list of objects saved in a text file that I can display onto a form. However now I need a button that will only display certain objects from the list based on a property, in my case brand. Below is the code I've been trying to use but cant get it to work.
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
Underneath is the full code, in case more information is needed, thanks for your help.
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;
using System.IO;
namespace Car_Manager
{
public partial class Form1 : Form
{
string currentfile;
Car c;
int curIndex = -1;
List<Car> cars = new List<Car>();
public Form1()
{
InitializeComponent();
c = new Car();
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "myText";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
}
public void clearForm()
{
txtBrand.Text = "";
txtModel.Text = "";
txtYear.Text = "";
txtPrice.Text = "";
txtNumMiles.Text = "";
txtInformation.Text = "";
radAutomatic.Checked = false;
radManual.Checked = false;
radConvertible.Checked = false;
radCoupe.Checked = false;
radEstate.Checked = false;
radHatchback.Checked = false;
radHPV.Checked = false;
radSaloon.Checked = false;
radSUV.Checked = false;
}
private void DisplayCar()
{
txtBrand.Text = c.Brand;
txtModel.Text = c.Model;
txtYear.Text = c.Year;
txtPrice.Text = c.Price;
txtNumMiles.Text = c.NumMiles;
DisplayBody();
DisplayGear();
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void FormToObject()
{
c.Brand = txtBrand.Text;
c.Model = txtModel.Text;
c.Year = txtYear.Text;
c.Price = txtPrice.Text;
c.NumMiles = txtNumMiles.Text;
BodyCheck();
GearCheck();
}
private void BodyCheck()
{
if (radHatchback.Checked == true)
{ c.Body = radHatchback.Text; }
else if (radHPV.Checked == true)
{ c.Body = radHPV.Text; }
else if (radSUV.Checked == true)
{ c.Body = radSUV.Text; }
else if (radSaloon.Checked == true)
{ c.Body = radSaloon.Text; }
else if (radConvertible.Checked == true)
{ c.Body = radConvertible.Text; }
else if (radCoupe.Checked == true)
{ c.Body = radCoupe.Text; }
else if (radEstate.Checked == true)
{ c.Body = radEstate.Text; }
}
private void DisplayBody()
{
if (c.Body == "Hatchback")
{ radHatchback.PerformClick(); }
else if (c.Body == "HPV")
{ radHPV.PerformClick(); }
else if (c.Body == "SUV")
{ radSUV.PerformClick(); }
else if (c.Body == "Convertible")
{ radConvertible.PerformClick(); }
else if (c.Body == "Saloon")
{ radSaloon.PerformClick(); }
else if (c.Body == "Coupe")
{ radSaloon.PerformClick(); }
else if (c.Body == "Estate")
{ radEstate.PerformClick(); }
}
private void GearCheck()
{
if (radAutomatic.Checked == true)
{ c.GearBox = radAutomatic.Text; }
else if (radManual.Checked == true)
{ c.GearBox = radManual.Text; }
}
private void DisplayGear()
{
if (c.GearBox == "Manual")
{ radManual.PerformClick(); }
else if (c.GearBox == "Automatic")
{ radAutomatic.PerformClick(); }
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
currentfile = openFileDialog1.FileName;
saveToolStripMenuItem.Enabled = true;
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
while (reader.Peek() != -1)
{
string str = reader.ReadLine();
Car c = new Car();
c.ReadString(str);
cars.Add(c);
}
curIndex = 0;
c = cars[curIndex];
DisplayCar();
reader.Close();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save everything in a dialog box
saveFileDialog1.ShowDialog();
// Open the file and save the information
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
FormToObject();
string str = c.GetToString();
writer.WriteLine(str);
writer.Close();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save the file with the current file name
FileStream f1 = new FileStream(currentfile, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(f1);
// get the object into a string
FormToObject();
StreamWriter file = new System.IO.StreamWriter(f1);
cars.ForEach(file.WriteLine);
file.Close();
}
private void btnAddInfo_Click(object sender, EventArgs e)
{
c.Information.Add(txtAddInfo.Text);
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInformation.Text = "";
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void btnPreviousCar_Click(object sender, EventArgs e)
{
curIndex--;
if (curIndex < 0)
curIndex = cars.Count - 1;
c = cars[curIndex];
DisplayCar();
}
private void btnNextCar_Click(object sender, EventArgs e)
{
curIndex++;
if (curIndex >= cars.Count)
curIndex = 0;
c = cars[curIndex];
DisplayCar();
}
private void button1_Click(object sender, EventArgs e)
{
int a = cars.Count;
textBox1.Text = Convert.ToString(cars[2]);
}
private void btnEditCar_Click(object sender, EventArgs e)
{
txtBrand.ReadOnly = false;
txtModel.ReadOnly = false;
txtYear.ReadOnly = false;
txtPrice.ReadOnly = false;
txtNumMiles.ReadOnly = false;
txtAddInfo.ReadOnly = false;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
private void yearToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
class Car
{
//List of properties
private string brand;
private string model;
private string year;
private string price;
private string numMiles;
private string body;
private string gearbox;
private List<string> information;
//Constructor
public Car() //Default Constructor
{
brand = "Unknown";
model = "Unknown";
year = "Unknown";
price = "Unknown";
numMiles = "Unknown";
information = new List<string>();
}
public Car(string str)
{
information = new List<string>();
ReadString(str);
}
public void ReadString(string str)
{
string[] words = str.Split('|');
int Nwords = words.Count();
brand = words[0];
model = words[1];
year = words[2];
price = words[3];
numMiles = words[4];
body = words[5];
gearbox = words[6];
information.Clear();
for (int i = 7; i < Nwords; i++)
information.Add(words[i]);
}
//Methods
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public string Year
{
get { return year; }
set { year = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
public string NumMiles
{
get { return numMiles; }
set { numMiles = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
public string GearBox
{
get { return gearbox; }
set { gearbox = value; }
}
public List<string> Information
{
get { return information; }
set { information = value; }
}
public string GetToString()
{
string str = "";
str += brand + "|";
str += model + "|";
str += year + "|";
str += price + "|";
str += numMiles + "|";
str += body + "|";
str += gearbox + "|";
for (int i = 0; i < information.Count(); i++)
str += information[i] + "|";
return str;
}
}
}
First thing that I noticed:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
// You already have list of cars, this line will copy your list
// into a new one, which is unnecessary work (you don't use it later).
// You don't need this:
List<Car> BrandSelect = new List<Car>(cars);
// the "c" here is not the "c" that is the field of your form
// it's a part of the syntax of linq query
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
// This method displays what is in the field "c" (this.c)
// ... and the content of "c" didn't change at all
DisplayCar();
}
the code here should be, for example:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
//beware this can be null
this.c = (from a in this.cars
where a.Brand == textBox1.Text
select a).FirstOrDefault();
}
[msdn] introduction to linq queries

I want to edit my program so rather than having user enter seat number in a text box to make reservation they can select it in the listbox

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;

Categories