How can I access these controls from a different class? - c#

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";

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 can I add "item" to arraylist, if checkbox is marked?

I'm still kinda new into c#, and I'm currently stucked in a project. So basically I've currently have a form consisting of 5 textboxes, one checkbox and a button. When the user fills in the information, and submitting without marking the checkbox, the information is stored in a arraylist. If the user signs up as a traindriver, and marks the traindriver checkbox and submits, then a "id" need to be passed in to the arraylist, aswell as all the other information like first name and last name etc.
Currently I have a person class, which works just fine. Then I have a subclass called traindrivers, which one consists of a "id" variable, that "increments" every time a new traindrivers is signed up, since they can't have the same number. So how can I add this "id" to the "personsArrayList" if the person that are signed up, are marked as a traindriver?
Form
I've tried to use the procedure as I've used when new Persons are added. But for some reason, I couldn't find the varaibles which contains the id.
public class Persons
{
//instance variables
private string firstname;
private string lastname;
private string email;
private int age;
//constructor
public Persons(string firstname, string lastname, string email, int age)
{
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.age = age;
}
public string FirstName
{
get { return firstname; }
set { firstname = value; }
}
public string LastName
{
get { return lastname; }
set { lastname = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public override string ToString()
{
return FirstName + " " + LastName + " - " + Email + " - " + Age + ".";
}
}
public class Traindrivers : Persons
{
protected int id;
protected static int mycounter;
public Traindrivers(int id, string firstname, string lastname, string email, int age) : base(firstname, lastname, email, age)
{
mycounter++;
id = mycounter;
}
public int LicensNumber
{
get { return id; }
set { id = value; }
}
public override string ToString()
{
return LicensNumber + FirstName + LastName + Email + Age;
}
}
----------- aspx page ---------
protected void Button1_Click(object sender, EventArgs e)
{
Persons p1 = new Persons(TextBoxFirstName.Text, TextBoxLastName.Text, TextBoxEmail.Text, Convert.ToInt32(TextBoxAge.Text));
personsArrayList.Add(p1);
//Session["trainpersons"] = personsArrayList;
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
// When the checkbox is marked, add "id" to the arraylist
}
protected void ShowButton_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
for (int i = 0; i < personsArrayList.Count; i++)
{
ListBox1.Items.Add(personsArrayList[i].ToString());
Console.WriteLine(i);
}
}
}
protected void trainBtn_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
for (int i = 0; i < traindriversArrayList.Count; i++)
{
ListBox1.Items.Add(traindriversArrayList[i].ToString());
}
}
The expected result is to add "id" whenever is it a traindriver, that signs up. And it is of course expected to go into the personsArrayList.
ok based on this new edit, everything will be ok with few minor changes.
first of all you do not need any counter, static id will be enough and because you want to increment that id, it should be initialized. and since it is going to work automatically, no need to take id as an argument
public class Traindrivers : Persons
{
protected int id=0;
// ^^
protected static int mycounter=0;
public Traindrivers(/*int id,*/ string firstname, string lastname, string email, int age) : base(firstname, lastname, email, age)
// ^^^^^^^^^
{
mycounter++;
id = mycounter;
}
public int LicensNumber
{
get { return id; }
set { id = value; }
}
public override string ToString()
{
return LicensNumber + FirstName + LastName + Email + Age;
}
}
when you want to use it, in Button1_Click method, first you check if that checkbox is checked or not, then behave based on that, like this:
protected void Button1_Click(object sender, EventArgs e){
if(CheckBox1.checked==true){//information is about a traindriver
Traindrivers t1 = new Traindrivers (TextBoxFirstName.Text, TextBoxLastName.Text, TextBoxEmail.Text, Convert.ToInt32(TextBoxAge.Text));
traindriversArrayList.Add(t1);
}
else{//information in textboxes is not about traindriver
Persons p1 = new Persons(TextBoxFirstName.Text, TextBoxLastName.Text, TextBoxEmail.Text, Convert.ToInt32(TextBoxAge.Text));
personsArrayList.Add(p1);
}
}

Having trouble with C# Properties, Constructors,and LINQ

The code below is not returning any values. I am trying to print customer name and balance where their balance is below $0. I believe my property may not be set the right way. I am new to object oriented programming and LINQ. Any help would be appreciable.
namespace LinqExample
{
class Customer
{
private string name, phone, address;
private int balance;
public string custData;
public string Name
{
get { return name; }
set { name = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public int Balance
{
get { return balance; }
set { balance = value; }
}
public Customer(string name, string phone, string address, int balance)
{
custData = name + phone + address + balance;
}
}
}
namespace LinqExample
{
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer("Amit", "123-456-789", "123 Any Road", 25));
customers.Add(new Customer("Ajay", "571-888-1234", "1234 Any Street", 50));
customers.Add(new Customer("John", "707-123-4560", "456 John Street", -10));
customers.Add(new Customer("Ashley", "707-123-8402", "789 Ashley Street", -20));
var overdue =
from cust in customers
where cust.Balance < 0
orderby cust.Balance ascending
select new { cust.Name, cust.Balance };
foreach (var cust in overdue)
{
Console.WriteLine($"Name = {cust.Name}, Balance = {cust.Balance}");
}
}
}
}
You need to set the members values:
public Customer(string name, string phone, string address, int balance)
{
this.name = name;
this.phone = phone;
this.address = address;
this.balance = balance;
custData = name + phone + address + balance;
}
You're not setting any of your properties other than "custdata", you need to set the rest of the properties in your constructor too.
As others have stated you're not assigning any of your properties to the passed in ctor values.
Either do what Romano suggested or use an object initializer.
Assign the properties in the constructor.
public Customer(string name, string phone, string address, int balance)
{
this.name = name;
this.phone = phone;
this.address = address;
this.balance = balance;
custData = name + phone + address + balance;
}
Object Initilizer with a default ctor.
customers.Add(new Customer
{
Name = "Bill",
Phone = "555-555-5555",
Address = "2345 Some street",
Balance = "100000000"
});
As a side note, instead of using that public field "custData" try overriding the ToString method to return all of that concatenated data.

Object reference not set to an instance of an object while Adding Parameter

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.

C# adding a row to a datagridview in another form

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.

Categories