How to list a list of classes in a listbox? - c#

I want to make a list with person's names, in a listbox. The names should be added using the textbox, and i am using a class for the name savement etc.
How can i show the name of the person that added info to a listbox, and only show the information to a richtextbox when the list is clicked/pressed?
class code
class Persoon
{
private string naam;
private string geslacht;
private double gewicht;
private double lengte;
public double bmi;
public string Naam
{
get { return naam; }
set { naam = value; }
}
public string Geslacht
{
get { return geslacht; }
set { geslacht = value; }
}
public double Gewicht
{
get { return gewicht; }
set { gewicht = value; }
}
public double Lengte
{
get { return lengte; }
set { lengte = value; }
}
public double Bmi
{
get { return bmi; }
set { bmi = value; }
}
public object Convert { get; internal set; }
public Persoon(string nm, string gt, int wt, int le)
{
naam = nm;
geslacht = gt;
gewicht = wt;
lengte = le;
}
public double BMI()
{
double bmiuitkomst = gewicht / Math.Pow(lengte / 100.0, 2);
return bmiuitkomst;
}
public override string ToString()
{
return "Persoon: " + Naam + " " + Geslacht;
}
form code
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
double gewicht = Convert.ToDouble(tb_gewicht.Text);
double lengte = Convert.ToDouble(tb_lengte.Text);
double bmiuitkomst = gewicht / Math.Pow(lengte / 100.0, 2);
Persoon nieuwbmi = new Persoon(naam, geslacht, Convert.ToInt32(gewicht), Convert.ToInt32(lengte));
rtb_uitkomst.Text = "Naam: "+ naam + Environment.NewLine + "Geslacht: " + geslacht + Environment.NewLine + "BMI: " + Convert.ToString(bmiuitkomst);
// rtb_uitkomst.Text = nieuwbmi.ToString();
List<string> uitkomsten = new List<string>();
foreach (var item in uitkomsten)
{
uitkomsten.Add(Convert.ToString(nieuwbmi));
}
// lb_list.(Convert.ToString(nieuwbmi));
lb_list.DataSource = uitkomsten;
}
}
thanks in advance.

You are declaring a variable uitkomsten locally in button1_Click. This variable exists only while the method is executed. To make it live during the whole lifetime of the form, declare it as a field of the form class (and remove the declaration from the button1_Click method)
public partial class Form1 : Form
private List<string> uitkomsten = new List<string>();
public Form1()
{
InitializeComponent();
}
...
}
Then you try to add a person with
foreach (var item in uitkomsten)
{
uitkomsten.Add(Convert.ToString(nieuwbmi));
}
This cannot work. The foreach loop loops as many times as there are elements in the uitkomsten list. But since the list is empty at the beginning, the Add method will never be executed. Remove the loop.
uitkomsten.Add(Convert.ToString(nieuwbmi));
Note that you could add persons directly to the list, if you had a List<Persoon>. The listbox automatically uses .ToString() to display objects.
uitkomsten.Add(nieuwbmi);
Another problem is that lb_list.DataSource = uitkomsten; always assigns the same list. Because of how the listbox is implemented, it does not notice any difference and will therefore not display new persons added. To work around this problem, assign null first.
lb_list.DataSource = null;
lb_list.DataSource = uitkomsten;
Also change the weight and length parameters to double in the constructor of Persoon. You have doubles everywhere else for these measurements. If you use auto-implemented properties, this simplifies the class
class Persoon
{
public string Naam { get; set; }
public string Geslacht { get; set; }
public double Gewicht { get; set; }
public double Lengte { get; set; }
public double Bmi { get; set; }
public Persoon(string nm, string gt, double wt, double le)
{
Naam = nm;
Geslacht = gt;
Gewicht = wt;
Lengte = le;
}
public double BMI()
{
return Gewicht / Math.Pow(Lengte / 100.0, 2);
}
public override string ToString()
{
return $"Persoon: {Naam} {Geslacht}";
}
}
The form then becomes (with a few additional tweaks)
public partial class Form1 : Form
{
private List<Persoon> uitkomsten = new List<Persoon>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
double gewicht = Convert.ToDouble(tb_gewicht.Text);
double lengte = Convert.ToDouble(tb_lengte.Text);
Persoon nieuwbmi = new Persoon(naam, geslacht, gewicht, lengte);
rtb_uitkomst.Text = $"Naam: {naam}\r\nGeslacht: {geslacht}\r\nBMI: {nieuwbmi.BMI()}";
uitkomsten.Add(nieuwbmi);
lb_list.DataSource = null;
lb_list.DataSource = uitkomsten;
}
}

private List<string> uitkomsten = new List<string>();
private BindingSource bs = new BindingSource();
public MainForm()
{
InitializeComponent();
bs.DataSource = uitkomsten;
lb_list.DataSource = bs;
}
private void button1_Click(object sender, EventArgs e)
{
......
uitkomsten.Add(Convert.ToString(nieuwbmi));
bs.ResetBindings(false);
}
How can i make sure it only displays the info in the richtextbox when the name is selected (in the listbox)?
private void lb_list_SelectedIndexChanged(object sender, EventArgs e)
{
Persoon nieuwbmi = ((Persoon)lb_list.SelectedItem).Name1;
rtb_uitkomst.Text = "Naam: " + naam + Environment.NewLine + "Geslacht: " + geslacht + Environment.NewLine + "BMI: " + Convert.ToString(bmiuitkomst);
}

Related

How to get variabels from Class x and set them at Class y

For school im makeing a online shop application. i have 2 listboxes, one with products and one that is like a shopping cart:
Now i have the following classes:
public class Artikel
{
// instantie variabelen
private string artikelnaam;
private string categorie;
private double prijs;
// properties
public string Artikelnaam { get; }
public string Categorie { get; }
public double Prijs { get; }
// constructor
public Artikel(string artikelnaam, string categorie, double prijs)
{
this.artikelnaam = artikelnaam;
this.categorie = categorie;
this.prijs = prijs;
}
// ToString methode
public override string ToString()
{
return artikelnaam + "\t" + categorie + "\t" + prijs;
}
}
and the shopping cart class:
class WinkelwagenObject
{
// instantie variabelen
private string artikelnaam;
private string categorie;
private int aantal;
private double prijs;
private double subtotaal;
// properties
public string Artikelnaam { get; }
public string Categorie { get; }
public int Aantal { get; set; }
public double Prijs { get; }
public double Subtotaal { get; }
// constructor
public WinkelwagenObject(string artikelnaam, string categorie, int aantal, double prijs, double subtotaal)
{
this.artikelnaam = artikelnaam;
this.categorie = categorie;
this.aantal = aantal;
this.prijs = prijs;
this.subtotaal = subtotaal;
}
// ToString methode
public override string ToString()
{
return artikelnaam + "\t" + categorie + "\t" + aantal + "\t" + prijs + "\t" + subtotaal;
}
Now how do i selected a product in the lb of the products and send it too the shopping cart with the button "toevoegen"
You could make an Add-Method to the your Cart-Class that recieves an Artikel-Object and puts it into an Artikel-Collection like this:
public List<Artikel> ArtikelList { get; private set; }
public void Add(Artikel artikel)
{
if (ArtikelList == null)
ArtikelList = new List<Artikel>();
ArtikelList.Add(artikel);
}

Why is the order of the fields in datagridview wrong? (Reading file in datagridview)

Here is my primary abstract class Citizen containing essential attributes for the derived classes:
abstract class Citizen
{
public string firstname;
private string lastname;
private int age;
public string Name
{
get
{
return firstname;
}
set
{
firstname = value;
}
}
public string Surname
{
get
{
return lastname;
}
set
{
lastname = value;
}
}
public int Year
{
get
{
return age;
}
set
{
age = value;
}
}
}
And here is my derived class warrior:
class Warrior : Citizen
{
string weapon;
double height;
double weight;
public string Weapon
{
get
{
return weapon;
}
set
{
weapon = value;
}
}
public double Height
{
get
{
return height;
}
set
{
height = value;
}
}
public double Weight
{
get
{
return height;
}
set
{
height = value;
}
}
}
Program is rying to read the file and write it into the datagrid:
public partial class Form1 : Form
{
List<Warrior> values = new List<Warrior>();
Form2 form2 = new Form2(0);
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
int N = 0;
try
{
openFileDialog1.ShowDialog();
}
catch { MessageBox.Show("You have not chosen any files."); }
try
{
StreamReader read = new StreamReader(openFileDialog1.FileName,Encoding.Default);
do
{
read.ReadLine();
N++;
}
while (!read.EndOfStream);
Warrior[] warrior = new Warrior[N];
string[] temp;
read = new StreamReader(openFileDialog1.FileName, Encoding.Default);
for (int i = 0; i < N; i++)
{
temp = read.ReadLine().Split(' ');
warrior[i] = new Warrior();
warrior[i].Surname = temp[0];
warrior[i].Name = temp[1];
warrior[i].Year = int.Parse(temp[2]);
warrior[i].Weapon = temp[3];
values.Add(warrior[i]);
}
catch
{
MessageBox.Show("The file is either filled wrongly or corrupted.");
Application.Exit();
}
bindingSource1.DataSource = values;
dataGridView1.DataSource = bindingSource1;
this.Size = new Size(dataGridView1.Size.Width + 10, this.Size.Height);
}
And when I launch the program I get this:
So why have I got additional fields like weapon, height etc coming first? How to make it display name,surname and age first?

Need to Add 3 Day to current Transaction Date

I have a button that needs to add 3 days to the current transaction date already in ArrayList.
How to accomplish this?
The code is as follows:
private void btnCheckCleared_Click(object sender, EventArgs e)
{
foreach (Transaction item in tranArray)
{
if (What goes here?)
{
DateTime.Today.AddDays(3).ToLongDateString();
}
}
}
If you need any more code, please let me know.
So here is my Transaction.cs code:
namespace TEXT TEXT TEXT
{
public class Transaction
{
//data hiding (blackbox)
//visible only to class itself
//fields (variables)
//4 member variables (instantiate object)
private decimal decAmount;
private DateTime dteTransactionDate;
private string strCheckNumber;
private string strPayee;
private string strTypeTrans;
public bool CheckCleared;
public decimal Amount
{
get
{
return decAmount;
}
set
{
decAmount = value;
}
}
public string CheckNumber
{
get
{
return strCheckNumber;
}
set
{
strCheckNumber = value;
}
}
public string Payee
{
get
{
return strPayee;
}
set
{
strPayee = value;
}
}
public DateTime TransactionDate
{
get
{
return dteTransactionDate;
}
set
{
dteTransactionDate = value;
}
}
public TransactionType TypeTrans;
//constructor
public Transaction(string payee, decimal amount, TransactionType typeTrans, DateTime transactionDate)
{
this.Payee = payee; //assignment operator =
this.Amount = amount; //this is to qualify
this.TypeTrans = typeTrans;
this.TransactionDate = transactionDate;
}
public Transaction(string payee, decimal amount, TransactionType typeTrans, DateTime transactionDate, string checkNumber)
{
this.Payee = payee; //assignment operator =
this.Amount = amount; //this is to qualify
this.CheckNumber = checkNumber;
this.TypeTrans = typeTrans;
this.TransactionDate = transactionDate;
}
//public Transaction ()
public override string ToString()
{
return this.TransactionDate.ToShortDateString() + " " + this.Amount.ToString("C") + "\t" + this.TypeTrans;
}
}
}
You need something like that:
private void btnCheckCleared_Click(object sender, EventArgs e)
{
foreach (Transaction item in tranArray)
{
if (/*Whatever your condition looks like*/)
{
item.TransactionDate = item.TransactionDate.AddDays(3);
}
}
}
AddDays does not modify the given DateTime but returns a new DateTime, that's why it is assigned back to item.TransactionDate

C# array to save data

I am new with C# and i have a problem. Actually it's my first year in college and in programming and i have a problem with arrays. I've made a class with 3 constructors and 1 method in Windows Form Application. The problem is that i want to store data from three textBoxes - that the user is typing- into an array of 10 using a button. and i don't know how to do it.
public class Employee
{
private int idnum;
private string flname;
private double annual;
public Employee()
{
idnum = 0;
flname = "";
annual = 0.0;
}
public Employee(int id, string fname)
{
idnum = id;
flname = fname;
annual = 0.0;
}
public Employee(int id, string fname, double ann)
{
idnum = id;
flname = fname;
annual = ann;
}
public int idNumber
{
get { return idnum; }
set { idnum = value; }
}
public string FLName
{
get { return flname; }
set { flname = value; }
}
public double Annual
{
get { return annual; }
set { annual = value; }
}
public string Message()
{
return (Convert.ToString(idnum) + " " + flname + " " + Convert.ToString(annual));
}
}
First of all you should add on this form 3 textboxe elements and name it in a next manner textBoxId, textBoxFLName, textBoxAnnual
Also you have to add a button. Let's call it btnSave
Write an event OnClick for this button. In this method we must read all data which user fill in on the form.
List<Employee> allEmployees = new List<Employee>();
private void buttonSave_Click(object sender, EventArgs e)
{
//read user input
int empId = Int32.Parse(textBoxId.Text);
string empFlName = textBoxFLName.Text;
double empAnnual = double.Parse(textBoxAnnual.Text);
// create new Employee object
Employee emp = new Employee(empId, empFlName, empAnnual);
// add new employee to container (for example array, list, etc).
// In this case I will prefer to use list, becouse it can grow dynamically
allEmployees.Add(emp);
}
And you can also rewrite your code in a little bit shortest manner:
public class Employee
{
public int IdNum { get; set; }
public string FlName { get; set; }
public double Annual { get; set; }
public Employee(int id, string flname, double annual = 0.0)
{
IdNum = id;
FlName = flname;
Annual = annual;
}
public override string ToString()
{
return (Convert.ToString(IdNum) + " " + FlName + " " + Convert.ToString(Annual));
}
}

showing form by select from list invalid cast exception

I want to add two lists to the box. It doesn't have a problem with adding items to the listbox, but a problem occurs when I try to click on one of the items and show a related form with details filled in to allow users to make amendments. Obviously the form didn't show, but instead an error occurs, no matter if I was try to open the form "delivery" or "pickup". The problem still occurs on one line
Error:
An unhandled exception of type 'System.InvalidCastException' occurred
in coursework2.exe
Additional information: Unable to cast object of type 'System.String'
to type 'coursework2.Pickup'.
namespace coursework2
{
public partial class MainForm : Form
{
private DeliveryForm deliveryform = new DeliveryForm();
private List<Visit> requests = new List<Visit>();
private Visit theVisit = new Visit();
private PickupForm pickupform = new PickupForm();
public void requestVisit(Visit newVisit)
{
requests.Add(newVisit);
}
public MainForm()
{
InitializeComponent();
}
private void btnNpickup_Click(object sender, EventArgs e)
{
pickupform.pickup = new Pickup();
pickupform.ShowDialog();
if (pickupform.pickup != null)
{
Pickup newPu = pickupform.pickup;
theVisit.addPick(newPu);
List<String> listOfPic = theVisit.listofPicks();
listboxVisits.Items.AddRange(listOfPic.ToArray());
}
updateList();
//this will upload details from pickup form to the list
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void btnNdelivery_Click(object sender, EventArgs e)
{
deliveryform.delivery = new Delivery();
deliveryform.ShowDialog();
if (deliveryform.delivery != null)
{
Delivery newDe = deliveryform.delivery;
theVisit.addDeliver(newDe);
List<String> listOfDel = theVisit.listofDeliver();
listboxVisits.Items.AddRange(listOfDel.ToArray());
}
updateList();
//this will upload detail of the delivery to the list
}
private void btnVall_Click(object sender, EventArgs e)
{
}
private void updateList()
{
listboxVisits.Items.Clear();
List<String> listofVis = theVisit.LisitVisits();
listboxVisits.Items.AddRange(listofVis.ToArray());
}
private void listboxVisits_SelectedIndexChanged(object sender, EventArgs e)
{
listboxVisits.FormattingEnabled = false;
int index = listboxVisits.SelectedIndex;
if (listboxVisits.SelectedItems.Count>0)
{
object object1 = listboxVisits.SelectedItems[0];
if (object1 is Delivery)
{
Delivery deliver = (Delivery)object1;
deliveryform.delivery = deliver;
deliveryform.ShowDialog();
}
else
{
Pickup pick = (Pickup)object1;// this is where error occur
pickupform.pickup = pick;
pickupform.ShowDialog();
}
}
this is the pickup class
public class Pickup
{
private string pickupname;
private string pickupaddress;
private Visit collects;
private Delivery sends;
private DateTime pdatetime;
private string dname;
private string daddress;
private DateTime dtime;
public string PickupName
{
get { return pickupname; }
set { pickupname = value; }
}
public string PickupAddress
{
get { return pickupaddress; }
set { pickupaddress = value; }
}
public string Dname
{
get { return dname; }
set { dname = value; }
}
public string Daddress
{
get { return daddress; }
set {daddress = value; }
}
public DateTime Pdatetime
{
get { return pdatetime; }
set { pdatetime = value; }
}
public DateTime Dtime
{
get { return dtime; }
set { dtime = value; }
}
public override string ToString()
{
return pickupname + " " + pickupaddress + " " + pdatetime.ToString()+" "+dname+" "+daddress+" "+dtime.ToString()+" Pickup ";
}
}
this is the visit class
public class Visit : Customer
{
private Customer requester;
private DateTime datetime;
private Delivery reciever;
private Pickup collect;
public DateTime DateTime
{
get { return datetime; }
set { datetime = value; }
}
private List<Pickup> picks = new List<Pickup>();
private List<Visit> visits = new List<Visit>();
private List<Delivery> deliver = new List<Delivery>();
public void addDeliver(Delivery de)
{
//adding new Delivery ToString the visit
deliver.Add(de);
}
public List<String> listofDeliver()
{
List<string> listofDeliver = new List<string>();
foreach (Delivery de in deliver)
{
String deAsString = de.ToString();
listofDeliver.Add(deAsString);
}
return listofDeliver;
}
public Delivery getDeliver(int index)
{
int count = 0;
foreach (Delivery de in deliver)
{
if (index == count)
return de;
count++;
}
return null;
}
public void addPick(Pickup pu)
{
picks.Add(pu);
}
public List<String> listofPicks()
{
List<string> listofPicks = new List<string>();
foreach (Pickup pu in picks)
{
String puAsString = pu.ToString();
listofPicks.Add(puAsString);
}
return listofPicks;
}
public Pickup getPicks(int index)
{
int count = 0;
foreach (Pickup pu in picks)
{
if (index == count)
return pu;
count++;
}
return null;
}
public List<String> LisitVisits()
{
List<String> visits = new List<string>();
visits.AddRange(listofDeliver());
visits.AddRange(listofPicks());
return visits;
}
public Visit getVisits(int index)
{
int count = 0;
foreach (Visit vis in visits)
{
if (index == count)
return vis;
count++;
}
return null;
}
public string VisitDetails()
{
return collect.PickupName + " " + collect.PickupAddress + " Pickup " + reciever.DeliveryName + " " + reciever.DeliveryAddress + " Delivery";
}
}

Categories

Resources