Populate listbox from text file - c#

I am making an contact book to try to learn classes, and opening new forms.
I am trying to get items from a text document to populate a list box, using only the string before the first delimiter from each line. When I run the script, the Windows form appears, but the listbox is blank but there appears to be five items in it that are selectable. Clicking on them has no effect.
Here is my code for the form:
namespace AddressBook
{
public partial class formMain : Form
{
//Pub vars
string selectedName = "";
List<string> values = new List<string>();
public formMain()
{
InitializeComponent();
}
public void formMain_Load (object sender, EventArgs e)
{
//load values from file
try
{
StreamReader inputFile;
inputFile = File.OpenText("EmpRoster.txt");
string lines;
while (!inputfile.EndOfSteam)
{
lines = inputFile.ReadLine();
string[] tokens = lines.Split(',');
PersonEntry person = new PersonEntry(tokens[0], tokens[1], tokens[2]);
values.Add(person.Name + ";" + person.Email + ";" + person.Phone);
listOuput.Items.Add(person.Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Selected index change
private void listOutput_SelectedIndexChanged(object sender, EventArgs e)
{
selectedName = listOutput.SelectedItem.ToString();
Form newForm = new Form();
Label label1 = new Label();
label1.Size = new Size(270, 75);
label1.Location = new Point(10, 10);
foreach (string str in values)
{
if (str.Containes(selectedName))
{
string[] tokens = str.Split(';');
label1.text += "Name: " + tokens[0] + "\n" + "Email: " + tokens[1] + "\n" + "Phone Number: " + tokens[2] + "\n";
}
}
newForm.Controls.Add(label1);
newForm.ShowDialog();
}
}
and here is my code for the class:
namespace AddressBook
{
public class PersonEntry
{
private string _name;
private string _email;
private string _phone;
public PersonEntry(string name, string email, string phone)
{
_name = "";
_email = "";
_phone = "";
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
{
public string Phone
{
get { return _phone; }
set { _phone = value; }
}
}
}
I cannot seem to get this to show at run; however, I did try adding a button and populating the listbox on click, and that seemed to work.
I'd appreciate some fresh eyes on this.

The problem lies on how you are instantiating your class. If you look at the constructor:
public PersonEntry(string name, string email, string phone)
{
_name = "";
_email = "";
_phone = "";
}
You are not storing the received values, but ignoring them completely. Just simplify your class to this:
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public PersonEntry(string name, string email, string phone)
{
Name = name;
Email = email;
Phone = phone;
}
You don't need to generate the backing fields, that's done automatically for you.

Your PersonEntry constructor is the issue. You are assigning empty strings where you should (presumably) be assigning the supplied parameters.

Related

no argument given that corresponds to required format parameter error

i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.

how to add instance to the list and then to the listbox in windows form

I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.
Here is the code I have written so far but I'm stuck here and I don't know what to do next.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Album> AlbumList = new List<Album>();
private void TrackButton_Click(object sender, EventArgs e)
{
addTracks settingsForm = new addTracks();
settingsForm.ShowDialog();
}
private void CreateButton_Click(object sender, EventArgs e)
{
Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);
AlbumList.Add(g);
}
}
I dont have eny error i just think it is not creating a new list when I'm debuging the program.
This is the code for the class:
eclass Album
{
private string ASIN;
private string AlbumName;
private string Artist;
private string ReleaseDate;
private string Label;
private string Image;
public Album(int ASIN)
{
this.ASIN = "no value";
this.AlbumName = "no value";
this.Artist = "no value";
this.ReleaseDate = "no value";
this.Label = "no value";
this.Image = "no value";
}
public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
string Label, string Image)
{
this.ASIN = ASIN;
this.AlbumName = AlbumName;
this.Artist = Artist;
this.ReleaseDate = ReleaseDate;
this.Label = Label;
this.Image = Image;
}
public string aSIN
{
get { return this.ASIN; }
set { ASIN = value; }
}
public string albumName
{
get { return this.AlbumName; }
set { AlbumName = value; }
}
public string artist
{
get { return this.Artist; }
set { Artist = value; }
}
public string createDate
{
get { return this.ReleaseDate; }
set { ReleaseDate = value; }
}
public string label
{
get { return this.Label; }
set { Label = value; }
}
public string image
{
get { return this.Image; }
set { Image = value; }
}
}
Okay, you've got a few different options, but the easiest is something like this:
private void RefreshListBox()
{
myGuiListBox.Items.Clear();
foreach(Album loopAlbum in this.AlbumList)
{
myGuiListBox.Items.Add(loopAlbum.ToString());
}
}
... then, whenever something would change the list box (such as creating a new album and adding it to your List<>), you simply call the RefreshListBox() function.
I solved the listbox by not adding in the list box but just showing the values through the labels.
private void ShowAlbumsButton_Click(object sender, EventArgs e)
{
int temp = AlbumList.Count();
string talbumname = "";
string talbumasin = "";
string talbumartist = "";
string talbumrelease = "";
string talbumlabel = "";
for (int n =0; n<temp;n++)
{
talbumname = talbumname + AlbumList[n].albumName;
talbumname = talbumname + '\n';
talbumasin = talbumasin + AlbumList[n].aSIN;
talbumasin = talbumasin + '\n';
talbumartist = talbumartist + AlbumList[n].artist;
talbumartist = talbumartist + '\n';
talbumrelease = talbumrelease + AlbumList[n].createDate;
talbumrelease = talbumrelease + '\n';
talbumlabel = talbumlabel + AlbumList[n].label;
talbumlabel = talbumlabel + '\n';
}
label8.Text = talbumname;
label7.Text = talbumasin;
label9.Text = talbumartist;
label10.Text = talbumrelease;
label11.Text = talbumlabel;
}
thanks everyone for help.

sort text file by property (e.g. .last_name)

I've searched StackOverflow for an answer to this, but can't find a clear answer.
I've this Player Class (Yes i've posted the class before)
namespace Tennis_Match
{
class Player
{
private string first_name;
private string middle_name;
private string last_name;
private DateTime dob;
private string nat;
private char gender;
public string First_name { get { return first_name; } set { first_name = value; } }
public string Middle_name { get {return middle_name; } set { middle_name = value; } }
public string Last_name { get { return last_name; } set { last_name = value; } }
public DateTime Dob { get { return dob; } set { dob = value; } }
public string Nat { get { return nat; } set { nat = value; } }
public char Gender { get { return gender; } set { gender = value; } }
public Player(string first_name, string last_name, string middle_name, DateTime dob, string nat, char gender)
{
this.first_name = first_name;
this.last_name = last_name;
this.middle_name = middle_name;
this.dob = dob;
this.nat = nat;
this.gender = gender;
}
public override string ToString()
{
return first_name + " " + middle_name + " " + last_name + " " + dob + " "+ nat + " " + gender;
}
public static int CalculateAge(DateTime dob)
{
int years = DateTime.Now.Year - dob.Year;
if ((dob.Month > DateTime.Now.Month) || (dob.Month == DateTime.Now.Month && dob.Day > DateTime.Now.Day))
years--;
return years;
}
private List<string> content = new List<string>();
public string FileName { get; set; }
public string Delimiter { get; set; }
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
par.Close();
}
public void RunReadCSVFile(string fn, string delim = "|")
{
FileName = fn;
Delimiter = delim;
Load();
}
public string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName))
{
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}
}
}
Then I've another class tournament. I want to sort a textfile by among other Last_name. I've got an idea that i might need to use IComparable to sort the file.
The file is structured like this:
1|Mariuss|Luka|Thygesen|1986-07-25|NAURU|NR
First you have nothing to sort. So add to class
static List<Player> players = new List<Player>();
Next you need to add items to List in following function
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
//-----------------------------Add -----------------------
Player newPlayer = new Player(fields[0], fields[1], fields[2], DateTime.Parse(fields[3]), fields[4], fields[5][0]);
players.Add(newPlayer);
}
par.Close();
}
Now you have something to sort. So add a sort method (or CompareTo())
public void Sort()
{
players = players.OrderBy(x => new { x.last_name, x.first_name, x.middle_name }).ToList();
}

Regarding List<> declaration in C#

I'm trying to learn List<> in C#. I made a test program that takes the result of three textboxes and inputs it in a multiline textbox, after I put them in a list (to later save the list to file).
Here is my class declaration:
public class Film
{
public Film (string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
}
Now I instantiate the list:
List<Film> ListeFilms = new List<Film>();
And here is my event:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.ToString());
}
}
Now when I run, all that is written in the text box is:
test_1.Form1+Film
What did I do wrong?
You have to override the ToString() method in the Film class declaration.Otherwise it returns the type name.
Example:
public class Film
{
public Film(string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
public override string ToString()
{
return Numero.ToString() + " " + Titre.ToString() + " " + Categorie.ToString();
}
}
You just have to concatenate the three fields into the AppendText function:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.Numero + " - " + x.Titre + "- " + x.Categorie));
}
}

How can I access these controls from a different class?

I have a form (Edit) with some textbox controls as private members with public properties that I want to access from another class (PatientService) and I can't figure out how to overcome the "textbox does not exist in the current context" errors for the 8 controls I am trying to access. Also, is passing these values through the constructor a good way of doing this? I cannot have any other part of my project aside from the PatientService class interacting with the database. Thanks and the textboxes in question are in bold.
public partial class Edit : XtraForm
{
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
public Edit(string PatientID, string FirstName, string LastName, string Address, string City, string State, string ZipCode, string Phone)
{
InitializeComponent();
patientID = txtPatientID.Text;
firstName = txtFirstName.Text;
lastName = txtLastName.Text;
address = txtAddress.Text;
city = txtCity.Text;
state = txtState.Text;
zipCode = txtZipCode.Text;
phone = txtPhone.Text;
}
public string PatientID
{
get { return patientID; }
set { patientID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string ZipCode
{
get { return txtZipCode.Text; }
set { txtZipCode.Text = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public void CreatePatient()
{
//SAConnection conn = new SAConnection("dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
//SACommand cmd = new SACommand("INSERT INTO patient(patient_id, first_name, last_name, address, city, state, zipcode, phone) VALUES(); ");
using (SAConnection conn = new SAConnection())
{
conn.ConnectionString = "dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;";
conn.Open();
using (SACommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"insert into patient(\n" +
" patient_id,\n" +
" first_name,\n" +
" last_name,\n" +
" address,\n" +
" city,\n" +
" state,\n" +
" zipcode,\n" +
" phone)\n" +
" values(\n" +
" #prm_patient_id,\n" +
" #prm_first_name,\n" +
" #prm_last_name,\n" +
" #prm_address,\n" +
" #prm_city,\n" +
" #prm_state,\n" +
" #prm_zipcode,\n" +
" #prm_phone)";
cmd.Parameters.Add("#prm_patient_id", SADbType.VarChar, 80).Value = **txtPatientID.Text**;
cmd.Parameters.Add("#prm_first_name", SADbType.VarChar, 80).Value = **txtFirstName.Text**;
cmd.Parameters.Add("#prm_last_name", SADbType.VarChar, 80).Value = **txtLastName.Text**;
cmd.Parameters.Add("#prm_address", SADbType.VarChar, 80).Value = **txtAddress.Text**;
cmd.Parameters.Add("#prm_city", SADbType.VarChar, 80).Value = **txtCity.Text**;
cmd.Parameters.Add("#prm_state", SADbType.VarChar, 80).Value = **txtState.Text**;
cmd.Parameters.Add("#prm_zipode", SADbType.VarChar, 80).Value = **txtZipCode.Text**;
cmd.Parameters.Add("#prm_phone", SADbType.VarChar, 80).Value = **txtPhone.Text**;
cmd.ExecuteNonQuery();
}
}
}
Ok, so I'm still a little confused. I made the Patient class and instantiated it in the Edit form just like this.
public Patient pat;
public Edit(Patient patient)
{
InitializeComponent();
pat = patient;
}
I'm trying to get it to when I click on an "OK" button, the textbox controls are inserted into the database via a CreatePatient method in the PatientService class.
Here is the method from the Edit Form that invokes the CreatePatient method in the PatientService class:
private void btnOK_Click(object sender, EventArgs e)
{
PatientService ps = new PatientService();
ps.CreatePatient();
}
My Patient class looks like:
public class Patient
{
List<Patient> patList = new List<Patient>();
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
private int classificationID;
protected object Dispose;
public Patient(string PatientID, string FirstName, string LastName, string Address, string City, string State, string ZipCode, string Phone, int ClassificationID)
{
this.patientID = PatientID;
this.firstName = FirstName;
this.lastName = LastName;
this.address = Address;
this.city = City;
this.state = State;
this.zipCode = ZipCode;
this.phone = Phone;
this.classificationID = ClassificationID;
}
public string PatientId
{
get { return patientID; }
set { patientID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string ZipCode
{
get { return zipCode; }
set { zipCode = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public int ClassificationID
{
get { return classificationID; }
set { classificationID = value; }
}
public Patient(string PatientID)
{
this.patientID = PatientID;
}
public Patient()
{
}
}
}
So considering I am no longer passing values through the Edit constructor like in the beginning, how would I make use of the Patient class to get the textbox values sent to the database?
You do not need to access your controls from other form, or class.
Since you have public properties, you can access to it from parent form:
Edit form = new Edit(patientId, ...);
//after using form
string patientId = form.PatientID;
Better option is wrap your fields into a single object, like entity
public class Patient
{
private string patientID;
private string firstName;
private string lastName;
private string address;
private string city;
private string state;
private string zipCode;
private string phone;
//put here your properties
}
Use it in your Edit form
public partial class Edit : XtraForm
{
public Patient Patient;
public Edit() //empty constructor if you want to pass data manually via property
{
InitializeComponent();
}
public Edit(Patient patient)
{
InitializeComponent();
Patient = patient;
}
//full code here
}
You can always keep actual data in Patient object using EditValueChanged event form your text boxes (As far as I know you are using DevExpress controls, like XtraForm). For example:
private void txtPatientID_EditValueChanged(object sender, EventArgs e)
{
Patient.patientId = txtPatientID.Text;
}
You need to pass your form class to PatientService
For example:
public class PatientService
{
//your code
public Edit EditForm{get;set;}
}
Now you can pass Edit to PatientService:
somewhere:
var svc = new PatientService();
svc.EditForm = existEditForm;
You can access tour edit form from patient service now. Something like this:
EditForm.PatientId = "0";

Categories