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();
}
Related
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.
As seen below, I have:
A class (Viatura) that creates a Vehicle.
Another class (ArrayViatura) that creates an array of Vehicles and subsequent methods.
In the form, I have to let the user define the size of this array of vehicles (numericupdown1), before doing any other operations within the form.
How do I make this value become the array size?
Thanks in Advance!
Here's the Code:
Class Viatura
`namespace IP_GonçaloDias_G00
{
class Viatura
{
string cvMatrícula;
string cvMarca;
string cvModelo;
string cvAnoFabrico;
string cvTipoPropulsão;
string cvCilindrada;
string cvPotência;
double cvAceleração;
string cvConsumoMédio;
string cvCor;
int cvTipoVeículo;
string cvCaixa;
DateTime cvPrimeiraMatrícula;
int cvNúmeroRegistos;
double cvKMPercorridos;
string cvDescriçãoVeículo;
double cvPreçoAquisição;
double cvPreçoProposto;
double cvPreçoVenda;
DateTime cvDataVenda;
string cvNomeCliente;
public Viatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
string cvMatrícula=matricula;
string cvMarca=marca;
string cvModelo=modelo;
string cvAnoFabrico=anofabrico;
string cvTipoPropulsão=tipopropulsao;
string cvCilindrada=cilindrada;
string cvPotência=potencia;
double cvAceleração=aceleracao;
string cvConsumoMédio=consumomedio;
string cvCor=cor;
int cvTipoVeículo=tipoveiculo;
string cvCaixa=caixa;
DateTime cvPrimeiraMatrícula=primeiramatricula;
int cvNúmeroRegistos=numeroregistos;
double cvKMPercorridos=km;
string cvDescriçãoVeículo=descricaoveiculo;
double cvPreçoAquisição=precoaquisicao;
double cvPreçoProposto=precoproposto;
double cvPreçoVenda=precovenda;
DateTime cvDataVenda=datavenda;
string cvNomeCliente =nomecliente;
}
public string CVMatrícula
{
get { return cvMatrícula; }
set { cvMatrícula = value; }
}
public string CVMarca
{
get { return cvMarca; }
set { cvMarca = value; }
}
public string CVModelo
{
get { return cvModelo; }
set { cvModelo = value; }
}
public string CVAnoFabrico
{
get { return cvAnoFabrico; }
set { cvAnoFabrico = value; }
}
public string CVTipoPropulsão
{
get { return cvTipoPropulsão; }
set { cvTipoPropulsão = value; }
}
public string CVCilindrada
{
get { return cvCilindrada; }
set { cvCilindrada = value; }
}
public string CVPotência
{
get { return cvPotência; }
set { cvPotência = value; }
}
public double CvAceleração
{
get { return cvAceleração; }
set { cvAceleração = value; }
}
public string CVConsumoMédio
{
get { return cvConsumoMédio; }
set { cvConsumoMédio = value; }
}
public string CVCor
{
get { return cvCor; }
set { cvCor = value; }
}
public int CVTipoVeículo
{
get { return cvTipoVeículo; }
set { cvTipoVeículo = value; }
}
public string CVCaixa
{
get { return cvCaixa; }
set { cvCaixa = value; }
}
public DateTime CVPrimeiraMatrícula
{
get { return cvPrimeiraMatrícula; }
set { cvPrimeiraMatrícula = value; }
}
public int CVNúmeroRegistos
{
get { return cvNúmeroRegistos; }
set { cvNúmeroRegistos = value; }
}
public double CVKMPercorridos
{
get { return cvKMPercorridos; }
set { cvKMPercorridos = value; }
}
public string CVDescriçãoVeículo
{
get { return cvDescriçãoVeículo; }
set { cvDescriçãoVeículo = value; }
}
public double CVPreçoAquisição
{
get { return cvPreçoAquisição; }
set { cvPreçoAquisição = value; }
}
public double CVPreçoProposto
{
get { return cvPreçoProposto; }
set { cvPreçoProposto = value; }
}
public double CVPreçoVenda
{
get { return cvPreçoVenda; }
set { cvPreçoVenda = value; }
}
public DateTime CVDataVenda
{
get { return cvDataVenda; }
set { cvDataVenda = value; }
}
public string CVNomeCliente
{
get { return cvNomeCliente; }
set { cvNomeCliente = value; }
}
}
}`
The Class ArrayViatura
`namespace IP_GonçaloDias_G00
{
class ArrayViaturas
{
public Viatura[] viaturas;
private int numElementos;
private int pointer;
public ArrayViaturas(int nElem)
{
viaturas = new Viatura[nElem];
numElementos = 0;
pointer = 0;
}
public int NumElementos
{
set { numElementos = value; }
get { return numElementos; }
}
public int Pointer
{
set { pointer = value; }
get { return pointer; }
}
public void InserirViatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
viaturas[numElementos] = new Viatura(matricula, marca, modelo, anofabrico, tipopropulsao, cilindrada, potencia, aceleracao, consumomedio, cor, tipoveiculo, caixa, primeiramatricula, numeroregistos, km, descricaoveiculo, precoaquisicao, precoproposto, precovenda, datavenda, nomecliente);
numElementos++;
}
public string MostrarViatura(int index, string sep)
{
string str = viaturas[index].CVMatrícula + sep + viaturas[index].CVMarca + sep + viaturas[index].CVModelo + sep + viaturas[index].CVAnoFabrico +
sep + viaturas[index].CVTipoPropulsão + sep + viaturas[index].CVCilindrada + sep + viaturas[index].CVPotência +
sep + viaturas[index].CvAceleração.ToString("f2") + "KMh" + sep + viaturas[index].CVConsumoMédio + sep + viaturas[index].CVCor
+ sep + viaturas[index].CVTipoVeículo.ToString("f2") + sep + viaturas[index].CVCaixa + sep + viaturas[index].CVPrimeiraMatrícula.ToShortDateString()
+ sep + viaturas[index].CVNúmeroRegistos.ToString("f2") + sep + viaturas[index].CVKMPercorridos.ToString("f2") + sep + viaturas[index].CVDescriçãoVeículo +
sep + viaturas[index].CVPreçoAquisição.ToString("f2") + sep + viaturas[index].CVPreçoProposto.ToString("f2") + sep + viaturas[index].CVPreçoVenda.ToString("f2") +
sep + viaturas[index].CVNomeCliente;
return str;
}
public void EliminarViatura(int index)
{
for (int i = index; i < NumElementos - 1; i++)
{
viaturas[i] = viaturas[i + 1];
}
NumElementos--;
if (pointer == NumElementos)
pointer--;
}
}
}`
The Form Code
`namespace IP_GonçaloDias_G00
{
public partial class RegistoViaturas : Form
{
string cvMatrícula="";
string cvMarca = "";
string cvModelo = "";
string cvAnoFabrico = "";
string cvTipoPropulsão = "";
string cvCilindrada = "";
string cvPotência = "";
double cvAceleração = 0;
string cvConsumoMédio = "";
string cvCor = "";
int cvTipoVeículo = 0;
string cvCaixa = "";
DateTime cvPrimeiraMatrícula=DateTime.Now;
int cvNúmeroRegistos = 0;
double cvKMPercorridos = 0;
string cvDescriçãoVeículo = "";
double cvPreçoAquisição = 0;
double cvPreçoProposto = 0;
double cvPreçoVenda = 0;
DateTime cvDataVenda = DateTime.Now;
string cvNomeCliente = "";
public RegistoViaturas()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button7_Click(object sender, EventArgs e)
{
int size= Convert.ToInt32(numericUpDown1.Value);
ArrayViaturas viaturas = new ArrayViaturas(size);
MessageBox.Show("O tamanho definido para o Array é: " + viaturas.viaturas.Length);
groupBox2.Enabled = true;
}
}
}`
Assuming that the size is defined in TextBox1:
int size = 20;
int.TryParse(TextBox1.Text, out size);
public ArrayColab colaborators = new ArrayColab(size);
But note that its not a good idea to get the array size directly from user but you can define the array size yourself after detemening the user's need.
If the size is defined in NumericUpDown then:
public ArrayColab colaborators = new ArrayColab(NumericUpDown1.Value);
I want to update some information when a save button is clicked.
I got an error
On : command.Parameters.Add("#doctorID", SqlDbType.Int).Value =
resident.Doctor.DoctorID; Saying: Object reference not set to an
instance of an object.
Im guessing I need to create some kind of object?
Button code:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
Resident residentID;
txtAdditionalInformation.Text = hello.addtionalInformation;
txtForename.Text = hello.FirstName;
txtSurname.Text = hello.Surname;
txtTitle.Text = hello.Title;
ResidentData.Update(hello);
}
update code (ResidentData Class):
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}
*Residence Class:
{
public class Resident
{
private int residentID;
private string title;
private string firstName;
private string surname;
private string searchText;
private System.DateTime dateOfBirth;
private byte[] photo;
private Room room;
private Doctor doctor;
private string nhs;
private string residentBarcode;
private string allergies;
private string additionalInformation;
public Resident()
: base()
{
}
public Resident(int newResidentID, string newTitle, string newFirstName, string newSurname, string newSearchText, System.DateTime newDateOfBirth, byte[] newPhoto, Room newRoom, Doctor newDoctor, string newNhs, string newResidentBarcode, string newAllergies, string newAdditionalInformation)
: base()
{
residentID = newResidentID;
title = newTitle;
firstName = newFirstName;
surname = newSurname;
searchText = newSearchText;
dateOfBirth = newDateOfBirth;
photo = newPhoto;
room= newRoom;
doctor = newDoctor;
nhs = newNhs;
residentBarcode = newResidentBarcode;
allergies = newAllergies;
additionalInformation = newAdditionalInformation;
}
public int ResidentID
{
get { return residentID; }
set { residentID = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string SearchText
{
get { return searchText; }
set { searchText = value; }
}
public System.DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public byte[] Photo
{
get { return photo; }
set { photo = value; }
}
public Room Room
{
get { return room; }
set { room = value; }
}
public Doctor Doctor
{
get { return doctor; }
set { doctor = value; }
}
public string NHS
{
get { return nhs; }
set { nhs = value; }
}
public string ResidentBarcode
{
get { return residentBarcode; }
set { residentBarcode = value; }
}
public string Allergies
{
get { return allergies; }
set { allergies = value; }
}
public string addtionalInformation{
get { return additionalInformation; }
set { additionalInformation = value; }
}
}
}
Looking at the way you've created your Resident:
Resident hello = new Resident();
ucMedicationCheckIn.SaveCheckedInMedication();
ResidentData.Update(hello);
ucMedicationCheckIn.HideDetails();
you probably haven't assigned it a doctor which is why it fails on this line:
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
You need to initialize the Doctor type
Edit*
After seeing your Resident class I can see that you haven't initialized Room either.
You could provide a constructor to initialize these to default values:
public Resident()
{
this.Doctor = new Doctor();
this.Room = new Room();
//etc...
}
Though to do anything meaningful you will probably want to set these up with actual data before saving.
That is because your Doctor and Room are not initialized anyhere:
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
but that update will probably fail as there is no meaningful data in resident and rowsAffected will return 0 probably.
My problem is that I have a List<> variable connected to another class, and I want to get all the items from that List<> and put it into a string.
In the result string, i'd like to see callNum, copyNum, content, author, year, title
Here is where I'm trying to put it into a string
public class CItemControl
{
//declare a list variable
private List<CItem> mItems;
private CItem mNewItem;
//a method that instantiates the list
public CItemControl()
{
mItems = new List<CItem>();
}
//attribute to get all items
public List<CItem> Items
{
get { return mItems; }
}
public CItem NewItem
{
get { return mNewItem; }
}
//method to add item to the CItem list
public void AddItem(int callNum, int copyNum, string content, string author, string year)
{
mNewItem = new CItem(callNum, copyNum, content, author, year);
mItems.Add(mNewItem);
}
//method to return all items to a string
public CItem ListAllItems()
{
string allItems;
}
Here is the class where I'm trying to get the items from. There will be variables added later.
class CItem
{
//declare attributes
private string mTitle;
private string mAuthor;
private string mContent;
private string mYear;
private int mCopyNum;
private int mCallNum;
private bool mHold = false;
private bool mBorrowed = false;
private bool mShelf = false;
//overload a constructor
public CItem(int CallNum, int CopyNum, string Content, string Author, string Year)
{
callNum = CallNum;
copyNum = CopyNum;
content = Content;
author = Author;
year = Year;
}
//create the default constructor
public CItem()
{
callNum = 0;
copyNum = 0;
content = "";
author = "";
year = "";
}
//set attributes
public int callNum
{
get { return mCallNum; }
set { mCallNum = value; }
}
public string content
{
get { return mContent; }
set { mContent = value; }
}
public string author
{
get { return mAuthor; }
set { mAuthor = value; }
}
public string year
{
get { return mYear; }
set { mYear = value; }
}
public string title
{
get { return mTitle; }
set { mTitle = value; }
}
public int copyNum
{
get { return mCopyNum; }
set { mCopyNum = value; }
}
public bool hold
{
get { return mHold; }
}
public bool borrowed
{
get { return mBorrowed; }
}
public bool shelf
{
get { return mShelf; }
}
//display information for users
public string displayInfo()
{
return "Call Number: " + callNum + ". Copy Number: " + copyNum + ". Title: " + title +
". Author: " + author + ". Year Published: " + year + ". Content: " + content;
}
//new method to display status of item
public string displayStatus()
{
if (borrowed == true)
return "Item is currently being borrowed.";
if (shelf == true && hold == false)
return "Item is available for borrowing.";
else
return "Item is on hold";
}
Any help is much appreciated!
Thanks in advance.
ListAllItems shall look something like this
public string ListAllItems()
{
var sb = new StringBuilder(); // var is of type StringBuilder
mItems.ForEach(item => sb.Append(item.displayInfo());
return sb.ToString();
}
return String.Join("; ", allItems.Select(item => item.displayInfo()));
You don't provide a lot of informations on how and what informations you want in your result string.
Can't you achieve this objective with a simple loop ?
using System.Text;
(...)
public string ListAllItems()
{
StringBuilder allItems = new StringBuilder();
foreach(CItem itm in Items){
allItems.AppendLine(itm.displayInfo());
}
return allItems.ToString();
}
Stringbuilder is optional but is faster than string concatenation.
I don't normally like to add formatter methods to property bags like this. If you want the flexibility to change have many formatting implementations, you might want to make a seperate class do the formatting.
public interface IFormatter<in T>
{
string Format(T obj);
}
public class CItemFormatter : IFormatter<CItem>
{
public string Format(CItem item)
{
//formatting logic
}
}
I'm having difficulty trying to pass information from one form in which a user inputs a lot of employee data and presses a Submit button and the information is to display as an added row to a datagridview table. What can I do to fix this issue?
The code I have at present:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void getEmployeedata(Manager manager)
{
int age;
int years;
int salary;
manager.FirstName = firstnameBox.Text;
manager.LastName = lastnameBox.Text;
manager.Gender = genderBox.Text;
manager.Title = titleBox.Text;
manager.Exempt = exemptBox.Text;
if (int.TryParse(ageBox.Text, out age))
{
manager.Age = age;
if (int.TryParse(yearsBox.Text, out years))
{
manager.Years = years;
if (int.TryParse(salaryBox.Text, out salary))
{
manager.Salary = salary;
}
else
{
MessageBox.Show("Wrong salary input");
}
}
else
{
MessageBox.Show("Wrong Years input");
}
}
else
{
MessageBox.Show("Wrong age input");
}
}
private void submitButton_Click(object sender, EventArgs e)
{
Manager manager = new Manager();
getEmployeedata(manager);
EmployeeListing form2 = new EmployeeListing(manager.FirstName, manager.LastName, manager.Gender, manager.Age, manager.Years, manager.Title, manager.Exempt, manager.Salary);
form2.Show();
}
private void clearButton_Click(object sender, EventArgs e)
{
firstnameBox.Text = "";
lastnameBox.Text = "";
genderBox.Text = "";
ageBox.Text = "";
yearsBox.Text = "";
titleBox.Text = "";
exemptBox.Text = "";
salaryBox.Text = "";
}
}
class Employee
{
private string firstName = "";
private string lastName = "";
private string gender = "";
private int age = 0;
private int years = 0;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public int Years
{
get { return years; }
set { years = value; }
}
} //end Employee class
class Manager : Employee
{
private string title = "";
private string exempt = "";
private int salary = 0;
public string Title
{
get { return title; }
set { title = value; }
}
public string Exempt
{
get { return exempt; }
set { exempt = value; }
}
public int Salary
{
get { return salary; }
set { salary = value; }
}
} //end Manager class
Form2:
public partial class EmployeeListing : Form
{
public EmployeeListing(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
InitializeComponent();
employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
}
}
In your click handler, you are initializing a EmployeeListing form every time you click the button, and you probably only want to do this once.So, keep the instance of your EmployeeListing outside of the click handler and only create one instance of it so that you can access it on subsequent clicks. To keep adding data to the form, you could create a public method on the EmployeeListing form that adds the row data and then call this method from your click handler, using the instance of the form.
This is untested, but just to get you started...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void getEmployeedata(Manager manager)
{
int age;
int years;
int salary;
EmployeeListing form2;
manager.FirstName = firstnameBox.Text;
manager.LastName = lastnameBox.Text;
manager.Gender = genderBox.Text;
manager.Title = titleBox.Text;
manager.Exempt = exemptBox.Text;
if (int.TryParse(ageBox.Text, out age))
{
manager.Age = age;
if (int.TryParse(yearsBox.Text, out years))
{
manager.Years = years;
if (int.TryParse(salaryBox.Text, out salary))
{
manager.Salary = salary;
}
else
{
MessageBox.Show("Wrong salary input");
}
}
else
{
MessageBox.Show("Wrong Years input");
}
}
else
{
MessageBox.Show("Wrong age input");
}
}
private void submitButton_Click(object sender, EventArgs e)
{
Manager manager = new Manager();
getEmployeedata(manager);
if (form2 == null)
{
EmployeeListing form2 = new EmployeeListing();
form2.Show();
}
form2.AddRowData(manager.FirstName, manager.LastName, manager.Gender, manager.Age, manager.Years, manager.Title, manager.Exempt, manager.Salary);
}
private void clearButton_Click(object sender, EventArgs e)
{
firstnameBox.Text = "";
lastnameBox.Text = "";
genderBox.Text = "";
ageBox.Text = "";
yearsBox.Text = "";
titleBox.Text = "";
exemptBox.Text = "";
salaryBox.Text = "";
}
}
class Employee
{
private string firstName = "";
private string lastName = "";
private string gender = "";
private int age = 0;
private int years = 0;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public int Years
{
get { return years; }
set { years = value; }
}
} //end Employee class
class Manager : Employee
{
private string title = "";
private string exempt = "";
private int salary = 0;
public string Title
{
get { return title; }
set { title = value; }
}
public string Exempt
{
get { return exempt; }
set { exempt = value; }
}
public int Salary
{
get { return salary; }
set { salary = value; }
}
} //end Manager class
public partial class EmployeeListing : Form
{
public EmployeeListing()
{
InitializeComponent();
}
public AddRowData(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
}
}
You can create a DataTable on the EmployeeListing() constructor and set the DataSource:
public EmployeeListing(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
InitializeComponent();
//employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
DataTable dtSource = new DataTable();
dtSource.Columns.Add("firstname", typeof(string));
dtSource.Columns.Add("lastname", typeof(string));
dtSource.Columns.Add("gender", typeof(string));
dtSource.Columns.Add("age", typeof(string));
dtSource.Columns.Add("years", typeof(string));
dtSource.Columns.Add("title", typeof(string));
dtSource.Columns.Add("exempt", typeof(string));
dtSource.Columns.Add("salary", typeof(string));
DataRow dtRow;
dtRow = dtSource.NewRow();
dtRow[0] = firstname;
dtRow[1] = lastname;
dtRow[2] = gender;
dtRow[3] = age;
dtRow[4] = years;
dtRow[5] = Title;
dtRow[6] = exempt;
dtRow[7] = salary;
dtSource.Rows.Add(dtRow.ItemArray);
employeeList.DataSource = dtSource;
}
You should also out this in another function and not in the constructor if you will add rows to the gridview more than once.