Skylar Brown
Skylar Brown

Reputation: 41

How to populate list object from 2nd form

I am needing to add an object that has been created from a form to populate a listbox with the object already set up everything else is working but I have done a lot of research and cannot figure out why my list box will not populate.

I have tried researching to find how to transfer the data and object to my second form. I have tried Items.Add(TheObject). and Get/set.

public partial class AddForm : Form
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmpType { get; set; }
        public string Salary { get; set; }


        public AddForm()
        {
            InitializeComponent();
        }

        private void AddForm_Load(object sender, EventArgs e)
        {
            txtfirstName.Text = FirstName;
            txtLastName.Text = LastName;
            cbempType.Text = EmpType;
            txtSalary.Text = Salary;
        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            if (FirstName!="" || LastName!="" || EmpType!=""|| Salary!="")
            {
                txtfirstName.Text = FirstName;
                txtLastName.Text = LastName;
                cbempType.Text = EmpType;
                txtSalary.Text = Salary;
                Person person = new Person(FirstName, LastName, EmpType, Salary);
                listPerson.Items.Add(person);
            }

        }

The expected result would look like return

First Name: John Last Name: Doe Employee type: Salary Salary: $1000000

instead I get nothing

Also This works on my main form I just have no Idea how to send that object over to the main form to the listbox

Upvotes: 1

Views: 151

Answers (2)

Apoorva Asthana
Apoorva Asthana

Reputation: 76

To display Person object in this way "First Name: John Last Name: Doe Employee type: Salary Salary: $1000000" , as @Bonny said you have to implement .ToString() . Implementation of ToString() in your scenario happens in this way . Inside your person class add this function

 public override string ToString()
 {
     return  "First Name:"+ name + " " + "Last Name:" + LastName+ " " + "Employee type:" + EmpType + "Salary:" + Salary  ;
 }

Upvotes: 1

Bonny Limas
Bonny Limas

Reputation: 11

You need to declare the Person object as public in the AddForm property like you declare FirstName, LastName, etc.

After the AddBtn_Click, you create that object you close the AddForm Window and set the dialog result to OK.

in your mainform, you show dialog the AddForm using AddForm.ShowDialog() and wait for the DialogResult.OK then you access the Person object you created from the AddForm.

In regards to the ListBox not displaying, have you implemented .ToString() in your Person class?

Upvotes: 1

Related Questions