I am having a major issue making this work. All I need to do is make my array display.
namespace OOP_3
{
public partial class Add_Child : Form
{
public Add_Child()
{
InitializeComponent();
}
private void btnAddChild_Click(object sender, EventArgs e)
{
Mother m = new Mother();
m.MyChildren = new Child[3];
int ID = int.Parse(txtID.Text);
string FNAME = txtFname.Text;
string LName = txtLname.Text;
DateTime DOB = DateTime.Parse(txtDob.Text);
//Add children
label5.Text = m.GetMyChildrenDetails();
if (addtoarray(m,ID,FNAME,LName,DOB) == true)
{
MessageBox.Show("added", "Add Child");
}
else
{
MessageBox.Show("cannot add", "Child add - full");
}
}
public bool addtoarray(Mother m, int ID, string FNAME, string LName,DateTime DOB)
{
for (int i = 0; i < m.MyChildren.Length; i++)
{
if (m.MyChildren[i]== null)
{
m.MyChildren[i] = new Child(m); //See comment below
m.MyChildren[i].ChildId = ID;
m.MyChildren[i].FirstName = FNAME;
m.MyChildren[i].LastName = LName;
m.MyChildren[i].DateOfBirth = DOB;
return true;
}
}
return false;
}
}
}
From a code comment: This line destroys everything in the heap and recreate the array causing my to have values that will not show up in my label5.text ive been pondering researching for hours and i think iam either going insane or am just noobie at coding which iam :) please some help would be nice:)....
If needed, I will post my class's and main form up :)
public class Mother
{
//Fields
private int motherId;
private string firstName;
private string lastName;
private string mobile;
private Child[] myChildren; //mother "has a" many children
//props
public Child[] MyChildren
{
get { return myChildren; }
set { myChildren = value; }
}
public string Mobile
{
get { return mobile; }
set { mobile = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int MotherId
{
get { return motherId; }
set { motherId = value; }
}
//constructors
//methods
//Get Mother Details
public override string ToString()
{
return motherId + ", " + firstName + ", " + lastName + ", " + mobile;
}
//AddChild
public bool AddChild(Child myChild)
{
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
myChildren[i] = myChild;
return true;
}
}
return false;
}
//GetMyChildrenDetails
public string GetMyChildrenDetails()
{
string msg = "";
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
msg += "\n" + myChildren[i];
}
}
return msg;
}
public class Child
{
//fields
private int childId;
private string firstName;
private string lastName;
private DateTime dateOfBirth;
private Mother myMother; //child "has a" mother
//props
public Mother MyMother
{
get { return myMother; }
set { myMother = value; }
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int ChildId
{
get { return childId; }
set { childId = value; }
}
//constructors
//Child cannot be created without a mother
public Child(Mother myMother)
{
this.myMother = myMother;
}
//Child cannot be created without a mother
public Child(Mother myMother, int childId)
{
this.myMother = myMother;
this.childId = childId;
}
//methods
//Get Child Details
public override string ToString()
{
return childId + ", " + firstName + ", " + lastName + ", " + dateOfBirth;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void BtnAddChild_Click(object sender, EventArgs e)
{
Add_Child child = new Add_Child();
child.Show();
}
private void btnRegister_Click_1(object sender, EventArgs e)
{
//create a mother object
Mother m = new Mother();
m.MotherId = int.Parse(txtID.Text);
m.FirstName = txtFname.Text;
m.LastName = txtLname.Text;
m.Mobile = txtMobile.Text;
Giving the new child a reference to its parent object is not the cause of your issue. In summary, you state:
"to have values that will not show up in my label5.text "
This would indicate that it is either your binding that has an issue, you have not implemented INotifyPropertyChanged, or your UI updating mechanism is not working (if you are not using binding). As you haven't stated what you are using for the UI, that is about as much as I can help...
My suggestion, you may use List instead of array, because not all mothers have three children. Example code:
public static class Program
{
static void Main(string[] args)
{
Mother mother = new Mother {
FirstName = "M First", LastName = "M Last", Contact = "225632655"
};
//Add dependents
mother.AddChild(new Child{ChildID = 1, FirstName = "Child FirstName 1", LastName = "Child LastName 1"});
mother.AddChild(new Child{ChildID = 2, FirstName = "Child FirstName 2", LastName = "Child LastName 2"});
mother.AddChild(new Child{ChildID = 3, FirstName = "Child FirstName 3", LastName = "Child LastName 3"});
Console.WriteLine(mother);
//List all the mother dependents
foreach(Child c in mother.Children)
{
Console.WriteLine(c);
}
Console.ReadKey();
}
}
class Mother
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Contact {get; set;}
private List<Child> _child;
public Mother()
{
_child = new List<Child>();
}
public void AddChild(Child child)
{
_child.Add(child);
}
public List<Child> Children
{
get { return _child; }
}
public override string ToString()
{
return string.Format("{0}, {1} ({2})", LastName, FirstName, Contact);
}
}
class Child
{
public string FirstName {get; set;}
public string LastName {get; set;}
public int ChildID {get; set;}
public override string ToString()
{
return string.Format("{0} {1}, {2}", ChildID, LastName, FirstName);
}
}
I hope, this will help.
Related
Hi there I was wondering if its possible for me to create a method in my customer.cs to delete a customer depending on its ID. How I want this to work is that the user will select a customer from the list box which only shows the customers firstName and then hit delete which will delete the customer off the list box. But I want to somehow create a method in the customer.cs which will look at the ID then delete it if its the right one. Can this be done? Any help would be create thank you.
form.cs:
public partial class AddCustomer : Form
{
List<Customer> list = new List<Customer>();
Random rand = new Random();
public AddCustomer()
{
InitializeComponent();
}
// Adds Customer
private void buttonAddCustomer_Click(object sender, EventArgs e)
{
Customer customer = new Customer();
customer.customerId = rand.Next();
customer.firstName = textBoxfn.Text;
list.Add(customer);
listBoxCustomers.Items.Add(customer.firstName);
}
// Deletes Customer
private void buttonDeleteCustomer_Click(object sender, EventArgs e)
{
listBoxCustomers.Items.Remove(listBoxCustomers.SelectedItem);
}
}
}
Customer.cs:
public class Customer
{
public int customerId;
public string firstName;
public string lastName;
public string phoneNumber;
public string address;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string PhoneNumber
{
get { return phoneNumber; }
set { phoneNumber = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
}
}
One idea is to load your customer list into a BindingList<Customer>
Now with this approach you work from the BindingList and the selected index of the ListBox.
I used a pre-defined customer class I had.
public class Customer
{
public int CustomerIdentifier { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public int CountryIdentifier { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
Mocked data
public class MockedData
{
public static List<Customer> Customers() => new List<Customer>()
{
new Customer()
{
CustomerIdentifier = 1, FirstName = "Jim", LastName = "Adams",
Street = "120 Hanover Sq.", City = "London", PostalCode = "WA1 1DP",
CountryIdentifier = 19
},
new Customer()
{
CustomerIdentifier = 2, FirstName = "Mary", LastName = "Adams",
Street = "1 rue Alsace-Lorraine", City = "Toulouse", PostalCode = "31000",
CountryIdentifier = 8
},
new Customer()
{
CustomerIdentifier = 3, FirstName = "Karen", LastName = "White",
Street = "120 Hanover Sq.", City = "London", PostalCode = "WA1 1DP",
CountryIdentifier = 19
}
};
}
Form code
public partial class Form1 : Form
{
private readonly BindingList<Customer> _customersBindingList;
public Form1()
{
InitializeComponent();
_customersBindingList = new BindingList<Customer>(MockedData.Customers());
listBoxCustomers.DataSource = _customersBindingList;
}
private void RemoveCurrentButton_Click(object sender, EventArgs e)
{
if (listBoxCustomers.SelectedIndex > -1)
{
_customersBindingList.RemoveAt(listBoxCustomers.SelectedIndex);
}
RemoveCurrentButton.Enabled = listBoxCustomers.SelectedIndex > -1;
}
}
Here is the function to remove all customers with a certain id :
private void RemoveCustomer(int id)
{
list.RemoveAll(c => c.customerId == id);
}
I made a custom usercontrol which contains a label.
I have 3 string properties : firstName, lastName, fullName.
How can I set the label's text = FullName ?
public string firstName
{
get; set;
}
public string lastName
{
get; set;
}
public string fullName //this fails
{
get { return string.Format("{0} {1}", firstName, lastName); }
set { labelFullName.Text = value; }
}
Looks like Windows Form to me. In WPF you would be using labelFullName.Content property. Assuming you want to set the label as the fullname each time first name or last name changes, then one option would be to do this within your UserControl class:
private String _sFirstName = "";
private String _sLastName = "";
public String FirstName {
get { return _sFirstName; }
set { _sFirstName = value; UpdateLabel(); }
}
public String LastName {
get { return _sLastName; }
set { _sLastName = value; UpdateLabel(); }
}
public String FullName {
get { return _sFirstName + " " + _sLastName; }
}
private void UpdateLabel() {
// do within a UI thread to prevent threading issues
this.BeginInvoke((Action)(() => {
labelFullName.Text = this.FullName.Trim();
}));
}
I'm currently trying to C# asp.net and this was one of my old labs that I never attended and I'm looking for help on it.
Basically I want to be able to store details of the person I input onto a webpage and then bring them up in the About page.
I keep getting the error:
Error 1: Inconsistent accessibility: field type 'System.Collections.Generic.IList<Lab5.Person>' is less accessible than field 'Lab5._Default.PresentPerson'
My code:
Class Person:
{
class Person
{
string age;
string name;
string dob;
string telNo;
string gender;
string address;
public string Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string DOB
{
get { return dob; }
set { dob = value; }
}
public string TelNo
{
get { return telNo; }
set { telNo = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string enterPerson;
public Person(string name, string age, string dob, string telNo, string gender, string address)
{
Name = name;
Age = age;
DOB = dob;
TelNo = telNo;
Gender = gender;
Address = address;
}
public string PresentPerson()
{
return enterPerson = "Name: " + Name + "\n" + "Age: " + Age + "\n" + "Date of Birth: "
+ DOB + "\n" + "Telephone Number: " + TelNo + "\n" + "Gender: " + Gender + "\n" + "Address: "
+ Address;
}
}
}
Code behind the Default page:
{
public partial class _Default : Page
{
public static IList<Person> personList = new List<Person>();
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("You have successfully added a Person!");
personList.Add(new Person(TextBox1.Text, TextBox2.Text,
TextBox3.Text, TextBox4.Text, DropDownList1.Text, TextBox5.Text));
Session["Person"] = personList;
}
}
}
and code in the About page:
{
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["PersonList"] != null)
{
IList<Person> personList = (List<Person>)Session["PersonList"];
foreach (Person p in personList)
{
Response.Write(string.Format("Name :{0} and Age :{1}, DOB :{2}, TelNo, :{3}, Gender :{4}, Address :{5} ", p.Name, p.Age, p.DOB, p.TelNo, p.Gender, p.Address));
Response.Write("<br/>");
}
}
}
}
}
I know that there's probably a load of issues, but I am new to C#!
Your _Default page has a list of Person field. Person is internal, but _Default is public.
This is the inconsistency - clients of _Default would have access to these Person objects when they shouldn't. To fix, make Person public:
public class Person
{
....
You could, alternatively, make the field internal or private.
private static IList<Person> personList = new List<Person>();
You need to change class Person to public class Person
If something is public like the _Default class in your example every public thing on it also needs to be public. You can't have a public thing that is in fact private.
I am having trouble to fix the errors in my object oriented program in C#. The program has 9 classes and in the one class. The Error is Inconsistent accessibility: parameter type 'Employee.Employee' is less accessible than method 'Employee.EmployeeInput.CollectEmployeeInfo(Employee.Employee)'
on the coding
public static void CollectEmployeeInfo(Employee theEmployee)
{
theEmployee.Firstname = InputUtilities.getStringInputValue("First Name");
theEmployee.Lastname = InputUtilities.getStringInputValue("Last name");
theEmployee.Gender = InputUtilities.getCharInputValue("Gender");
theEmployee.Dependents = InputUtilities.getIntegerInputValue("# Dependents");
}
the CollectEmployeeInfo is what is showing the error and I am not sure what has to be done to the other classes to fix the error. Any help would be greatly appreciated
class Employee
{
public const double MIN_SALARY = 20000;
public const double MAX_SALARY = 100000;
public const int MIN_DEPENDENTS = 0;
public const int MAX_DEPENDENTS = 10;
public const string DEFAULT_NAME = "not given";
public const char DEFAULT_GENDER = 'U';
public const string DEFAULT_TYPE = "Generic Employee";
protected string firstName;
protected string lastName;
protected double annualSalary;
protected char gender;
protected int dependents;
protected static int numEmployees = 0;
protected Benefits employeeBenefits;
protected string employeeType;
public Employee()
{
firstName = DEFAULT_NAME;
lastName = DEFAULT_NAME;
annualSalary = MIN_SALARY;
dependents = MIN_DEPENDENTS;
numEmployees++;
employeeBenefits = new Benefits();
}
public Employee(string firstname, string lastname, char gender, int dependents, double annualsalary, Benefits employeeBenefits)
{
Firstname = firstname;
Lastname = lastname;
AnnualSalary = annualsalary;
Gender = gender;
Dependents = dependents;
EmployeeBenefits = employeeBenefits;
numEmployees++;
}
public Benefits EmployeeBenefits
{
get { return employeeBenefits; }
set
{
if (value == null)
employeeBenefits = new Benefits();
else
employeeBenefits = value;
}
}
public Employee(string employeeType)
: this()
{
EmployeeType = employeeType;
}
public string Firstname
{
get { return firstName; }
set
{
if (String.IsNullOrEmpty(value))
firstName = DEFAULT_NAME;
else
firstName = value;
}
}
public string Lastname
{
get { return lastName; }
set
{
if (String.IsNullOrEmpty(value))
lastName = DEFAULT_NAME;
else
lastName = value;
}
}
public double AnnualSalary
{
get { return annualSalary; }
set
{
if (value > MIN_SALARY & value < MAX_SALARY)
annualSalary = value;
else if (value < MIN_SALARY)
annualSalary = MIN_SALARY;
else
annualSalary = MAX_SALARY;
}
}
public char Gender
{
get { return gender; }
set
{
if (value == 'F')
gender = value;
else if (value == 'f')
gender = value;
else if (value == 'M')
gender = value;
else if (value == 'm')
gender = value;
else
gender = DEFAULT_GENDER;
}
}
public int Dependents
{
get { return dependents; }
set
{
if (value >= MIN_DEPENDENTS & value <= MAX_DEPENDENTS)
dependents = value;
else if (value < MIN_DEPENDENTS)
dependents = MIN_DEPENDENTS;
else
dependents = MAX_DEPENDENTS;
}
}
public static int NumEmployees
{
get { return numEmployees; }
}
public string EmployeeName
{
get { return firstName + " " + lastName; }
}
public string EmployeeType
{
get { return employeeType; }
set
{
if (String.IsNullOrEmpty(value))
employeeType = DEFAULT_TYPE;
else
employeeType = value;
}
}
public double CalculatePay()
{
return annualSalary / 52;
}
public double CalculatePay(double modifiedSalary)
{
AnnualSalary = modifiedSalary;
return AnnualSalary / 52;
}
public override string ToString()
{
string output;
output = "\n============ Employee Information ============";
output += "\n\t Type:\t" + employeeType;
output += "\n\t Name:\t" + firstName + " " + lastName;
output += "\n\t Gender:\t" + gender;
output += "\n\t Dependents:\t" + dependents;
output += "\n\tAnnual Salary:\t" + annualSalary.ToString("C2");
output += "\n\t Weekly Pay:\t" + CalculatePay().ToString("C2");
output += "\n\t" + employeeBenefits.ToString();
return output;
}
}
}
Employee type should be not less accessible than CollectEmployeeInfo.
So Employee should be defined as public "at least"
All of the types you need to pass to a method must be at least as accessible as that method. If Employee is a private or internal class it can't be passed to this method from outside that class/assembly.
Make Employee public and it should work.
I'm trying to move items to a listbox, but it's calling my listbox a method group. The program has multiple classes. Here's what I have at the moment...
private void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add("Full Name\tAddress\tPhone Number");
Person Customer = new Person();
Customer.FirstName = NameTextBox.Text;
Customer.LastName = NameTextBox2.Text;
Customer.Address = AddressTextBox.Text + AddressTextBox2.Text + AddressTextBox3.Text;
Customer.PhoneNumber = PhoneNumberMaskedTextBox.Text;
Listbox1.Items.Add = (Customer.FirstName + Customer.LastName + "/t" + Customer.Address + "/t" + Customer.PhoneNumber);
}
Person is another class. Here's the code for that...
class Person
{
string _FirstName;
string _LastName;
string _Address;
string _PhoneNumber;
//Constructor
public void CustomerInfo()
{
_FirstName = "";
_LastName = "";
_Address = "";
_PhoneNumber = "";
}
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 PhoneNumber
{
get { return _PhoneNumber; }
set { _PhoneNumber = value; }
}
}
In yor second Add call probably you wanted to have
Listbox1.Items.Add(...)
instead of
Listbox1.Items.Add = (
Something else incorrect on your code is constructor name for Person. It should be named Person since contructors have same name as the class.