C# array to save data - c#

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));
}
}

Related

How to list a list of classes in a listbox?

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);
}

When comparing List elements to a user entered string only the last entered list element seems to be compared

My program has a list of people and a list of events, and it is the job of the program to sell tickets to these events, to the people entered into the list.
I'm a the stage where I need to program in the function that allows the user to select the show/event they would like to buy tickets to. I have decided to do this by displaying the available events in a RichTextBox and asking the user to write the name of the event that they would like to buy tickets to. If this event is present then the program should advance to the customer details form; if not then it should reset the input TextBox and display an error message to the user - simple enough.
However, for some reason when I try to search the list and compare the String "chosenArtist" to the event.getArtist() method it returns as not found for items that are actually present in the list. The only item it actually seems to return is the last entered list item.
For example:
Clown
Singer
Dancer
The compare function would tell me that Clown and Singer do not exist, but that Dancer does.
I think its something to do with either the code I have inside my foreach loop, or the actual code for the Events class, but I just don't know.
Code for AddCustomer form
(Comparison is done inside btnFind_click)
public partial class AddCustomer : Form
{
//arrayList
List<Person> personList = new List<Person>();
List<Events> eventsList = new List<Events>();
//class
Person p = new Person();
Events ev = new Events();
//variables
String chosenArtist;
//constructors
public AddCustomer()
{
InitializeComponent();
}
public AddCustomer(List<Events> eventsList, List<Person> personList)
{
InitializeComponent();
this.personList = personList;
this.eventsList = eventsList;
}
private void btnHome_Click(object sender, EventArgs e)
{
formHome home = new formHome();
this.Hide();
home.Show();
}
private void AddCustomer_Load(object sender, EventArgs e)
{
//sets error label text to blank
lblCustomerError.Text = "";
//sets display for rich text box
rtbAddCust.Text = "Events\n";
foreach (Events ev in eventsList)
{
rtbAddCust.AppendText("Artist name: " + ev.getArtist() + "\n" +
"Event venue: " + ev.getVenue() + "\n" +
"Event date: " + ev.getDate() + "\n" +
"Capacity: " + ev.getCapacity() + "\n" +
"Price: £" + ev.getPrice() + "\n" +
"Remaining tickets: " + ev.getRemaining() + "\n\n");
}
//Ensures curser always starts at top of text box
rtbAddCust.SelectionStart = 0;
rtbAddCust.ScrollToCaret();
}
private void btnFind_Click(object sender, EventArgs e)
{
chosenArtist = txtFindArtist.Text;
foreach(Events ev in eventsList)
{
//compares chosen artist to list items to determine if present
if (ev.getArtist().ToLower().Equals(chosenArtist.ToLower()))
{
lblCustomerError.Text = "Artist found";
//do something
}
else
{
lblCustomerError.Text = "artist not found";
txtFindArtist.Clear();
}
}
}
}
Code for Events Class
public class Events
{
private String artist;
private String venue;
private String date;
private String capacity;
private String remaining;
private String price;
public Events() { }
public Events(String artist, String venue, String date, String capacity, String remaining, String price )
{
this.artist = artist;
this.venue = venue;
this.date = date;
this.capacity = capacity;
this.remaining = remaining;
this.price = price;
}
//setters
public void setArtist(String artist) { this.artist = artist; }
public void setVenue(String venue) { this.venue = venue; }
public void setDate(String date) { this.date = date; }
public void setCapacity(String capacity) { this.capacity = capacity; }
public void setRemaining(String remaining) { this.remaining = remaining; }
public void setPrice(String price) { this.price = price; }
//getters
public String getArtist() { return artist; }
public String getVenue() { return venue; }
public String getDate() { return date; }
public String getCapacity() { return capacity; }
public String getRemaining() { return remaining; }
public String getPrice() { return price; }
//toString
public override String ToString() { return artist + " " + venue + " " + date + " " + capacity + " " + remaining + " " + price; }
It might also be important to note that if for example inside the foreach loop I changed the text inside my RichTextBox to just print out the names of artist this works fine. It only seems to be when I try to compare these names to something that I have a problem.
Following event handler is causing issue. Check if, suppose I enter 'Singer' in textbox and click Find. It will compare it with first item Clown which results in mismatch, then it compares it with Singer which is a match. But you continue to compare it with next item Dancer which is again a mismatch. You need to break from loop once match is found:
private void btnFind_Click(object sender, EventArgs e)
{
chosenArtist = txtFindArtist.Text;
foreach(Events ev in eventsList)
{
//compares chosen artist to list items to determine if present
if (ev.getArtist().ToLower().Equals(chosenArtist.ToLower()))
{
lblCustomerError.Text = "Artist found";
//do something
break;//BREAK FROM LOOP
}
else
{
lblCustomerError.Text = "artist not found";
txtFindArtist.Clear();
}
}
}
A slight cleaner implementation may go like this:
private void btnFind_Click(object sender, EventArgs e)
{
chosenArtist = txtFindArtist.Text.ToUpperInvariant;
var found=false;
foreach(Events ev in eventsList)
{
if (ev.getArtist().ToUpperInvariant().Equals(chosenArtist))
{
found=true;
break;//BREAK FROM LOOP
}
}
if(found){
lblCustomerError.Text = "Artist found";
//Do booking stuff
}
else
{
lblCustomerError.Text = "Artist not found";
txtFindArtist.Clear();
}
}
EDIT:- As noted by #AlexiLevenkov you can take advantage of auto properties in C#. You Event class will look like this if coded by some C# dev.
public class Events
{
public String Artist {get;set;}
public String Venue {get;set;}
public String Date {get;set;}
public String Capacity {get;set;}
public String Remaining {get;set;}
public String Price {get;set;}
public Events() { }
public Events(String artist, String venue, String date, String capacity,
String remaining, String price )
{
Artist = artist;
Venue = venue;
Date = date;
Capacity = capacity;
Remaining = remaining;
Price = price;
}
public override String ToString()
{
return artist + " " + venue + " " + date + " " + capacity + " " +
remaining + " " + price;
}
}
Also do give a thought to take proper data types for Date, Price, Capacity etc.

issues calling another class

first class as follows:
public class employeeApp
{
public static void main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee( );
}
public void employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
employeeNumber = 123;
name = Cody;
dateOfHire = 01/01/11;
monthlySalary = 2500;
}
}
second class as follows:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
the problems I am getting are:
*In my employeeApp class "does not contain a "static" main method for suitable entry point"
*in my employeeApp class "the name Cody does not exist in current context
*in my employeeApp class relating to dateOfHire "cannot implicitly convert int to string
I'm doing this for a class and the assignment it:
Create a Employee class. Items to include as data members are employee number, name, date of hire, and monthly salary. Include appropriate constructors and properties. Override the ToString ( ) method to return all data members. Create a second class to test your Employee class.
Any help at all is greatly appreciated.
1.in C# we use Main(Capital M) so Main method should be :
static void Main()
2.You have to create the Constructor in your class employe
3.You have to assign String to the String variable but you are assigning date.
as below :
dateOfHire = 01/01/11;
in your constructor
4.Cody should be represented as String "Cody" in your Constructor
5.while assigning data to local variables in class use this to represent current object when assigning variable have same name
example : this.employeenumber=employeenumber;
file 1:
namespace employee
{
public class employeeApp
{
public static void Main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee(123,"Cody","11/11/11",24567);//call your constructor
}
}
}
file 2:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
namespace EmployeeProgram
{
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;
this.name = "Cody";
this.dateOfHire = "01/01/11";
this.monthlySalary = 2500;
}
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
}
Issue 1 - C# is case sensitive. Capitalize Main. The use of the public access modifier is not necessary and is generally not recommended for Main.
static void Main()
Issue 2 - For the second name = Cody; I guess you meant...name = "Cody";
Issue 3 - For the third issue you need to convert the int values to string by calling ToString() on int values. employeeNumber.ToString() and monthlySalary.ToString().
There are lots of issues here and they are all fairly basic. I recommend you use Google or explain why exactly you could not solve them. Otherwise it might appear you have not put forth the required effort to solve the problems yourself.
Issue 4 As for the I/O write problem you need to qualify using this keyword because of the naming conflict between your local variables and private fields:
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;//because you have naming collissions you need to use `this`
this.name = "Cody";
this.dateOfHire = "01 / 01 / 11";
this.monthlySalary = 2500;
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
Then Main
static void Main(string[] args)
{
employee e = new employee(1,"","",0);//these values are ignored the way you set this up
e.Print();
Console.ReadLine();
}

Get the properties of objects in array

I have a small problem here.
I have an array which holds some objects (which have properties, duh)
Now I want to sort them by an int property that they have. My qustion is not how to sort them, but how do I read the value of the property of the objects in the array?
private void WriteHighscoreToFile(int groesse, int minenAnzahl, int zeit, string name)
{
using (StreamWriter sw = new StreamWriter(#"C:\Users\tstadler\Desktop\Highscore.txt", true))
{
sw.WriteLine("Spieler: " + name + " Punkte: " + (groesse * minenAnzahl - zeit * 2) + " Groesse: " + groesse + " Minenanzahl " + minenAnzahl + " Zeit: " + zeit);
}
using (StreamReader sr = new StreamReader(#"C:\Users\tstadler\Desktop\Highscore.txt", true))
{
List<CreateNewHighscore> highScores = new List<CreateNewHighscore>();
while (sr.ReadLine() != null)
{
_objectProperties = sr.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
highScores.Add(new CreateNewHighscore(_objectProperties));
highscoreCount++;
}
_highscoresArray = highScores.ToArray();
vergleicheArray(_highscoresArray);
}
}
The Class:
public class CreateNewHighscore
{
public string _name;
public int _punkte;
public int _groesse;
public int _minenAnzahl;
public int _zeit;
public CreateNewHighscore(string[] infos)
{
_name = infos[1];
_punkte = int.Parse(infos[5]) * int.Parse(infos[7]) - 2 * int.Parse(infos[9]);
_groesse = int.Parse(infos[5]);
_minenAnzahl = int.Parse(infos[7]);
_zeit = int.Parse(infos[9]);
} }
My qustion is not how to sort them, but how do I read the value of the property of the objects in the array?
You expose it as a property; for example:
class CreateNewHighscore
{
string _name;
int _punkte, _groesse, _minenAnzahl, _zeit;
public string Name { get { return _name; } }
public int Punkte { get { return _punkte; } }
public int Groesse { get { return _groesse; } }
public int Zeit { get { return _zeit; } }
public int MinenAnzahl { get { return _minenAnzahl; } }
// constructor not shown
}
Then you can access that member from any array / list; for example:
highScores.Sort((x,y) => x.Punkte.CompareTo(y.Punkte));
or:
int firstPunkte = _highscoresArray[0].Punkte;
Your array is of type CreateNewHighscore[] so if you want to access property in classic way just use following line.
_highscoresArray[i].YourIntProperty
where "YourIntProperty" is desired int property.
Use LINQ OrderBy method:
_highscoresArray = highScores.OrderBy(h => h.Punkte).ToArray();
Where Punkte is a property of your CreateNewHighscore class:
public int _punkte; // public field
public Punkte // public property
{
get { return _punkte; }
set { _punkte = value; } // you may not need setter
}
BTW currently your class DO NOT have any properties. There are only public (after your last edit) fields. If you want to sort by field value then:
_highscoresArray = highScores.OrderBy(h => h._punkte).ToArray();
But I advice you to make fields private, or use auto implemented properties instead. And rename your class. Name is really awful and sounds like method name.
public class CreateNewHighscore
{
public string Name { get; private set; }
public int Punkte { get; private set; }
public int Groesse { get; private set; }
public int MinenAnzahl { get; private set; }
public int Zeit { get; private set; }
public CreateNewHighscore(string[] infos)
{
// check infos count
Name = infos[1];
Punkte = int.Parse(infos[5]) * int.Parse(infos[7]) -
2 * int.Parse(infos[9]);
Groesse = int.Parse(infos[5]);
MinenAnzahl = int.Parse(infos[7]);
Zeit = int.Parse(infos[9]);
}
}

Checking if a list of objects contains a property

Hi i have a list of objects and i need to find out if the id i have is already in the list. In the object class i have set the id and i just want to find out if the one that is entered in the Ui is already in use.
The Class
class Product
{
private string name = "";
private int id = 0;
private decimal Pvalue = 0.00m;
private static int lastId = 1;
public Product(string namep, decimal valuep)
{
this.name = namep;
this.id = lastId++;
this.Pvalue = valuep;
}
public override string ToString()
{
return name + " " + id + " "+ Pvalue;
}
public bool Equals(Product p)
{
return (p.id == this.id);
}
}
Me trying to work it out:
int id;
bool test = int.TryParse(textBoxId.Text, out id);
if(test)
{
if(Inv.Contains(id))
{
label2.Text = "you already have this id";
}else
{
label2.Text = "you can use this id";
}
}
If any one has a idea on why this is not working or a better way it would save my back side thank you.
Change private int id = 0; to public int Id { get; set; }. Also, change all the references from id to Id.
Add a using System.Linq to your business logic file.
Change if (Inv.Contains(id)) to if (Inv.Any(x => x.Id == id))

Categories

Resources