Question

I'm very new to programming and I'm having so much trouble trying to send information between forms.

My Current situation:

I have 2 forms and a class. My first form only contains a listbox while my second form contains several text boxes with a OK button. What I want to do is type information into form2's text boxes, hit OK and have all the info from each text box populate my form1's listbox. The information from form2 should all go on a single line of form1's listbox.

Now what I'm trying to do is add the information from form2's text boxes to my custom class and then pass that custom class to the listbox in form1. I'd greatly appreciate any help. Here is the code I have so far:

Form2:

public partial class frmProperties : Form
{
    private string empVar;

    public string EmployeeNew
    {
        get { return empVar; }
        set { empVar = value; }
    }

    public frmProperties()
    {
        InitializeComponent();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void btnOk_Click(object sender, EventArgs e)
    {
        string empVar;
        double salaryToDouble = Convert.ToDouble(txtSalary.Text);
        Employee testEmploy = new Employee(txtFirstName.Text, txtLastName.Text, txtEmpType.Text, salaryToDouble);
        empVar = Convert.ToString(testEmploy);
    }
}

Form1:

public partial class Form1 : Form
{
    //public vars for file access
    FileStream output;
    StreamReader fileReader;
    StreamWriter fileWriter;

    public Form1()
    {
        InitializeComponent();
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileChooser = new OpenFileDialog();

        fileChooser.Title = "Choose an employee file to open";
        fileChooser.Filter = "Text Files (*.txt)|*.txt";

        DialogResult result = fileChooser.ShowDialog();

        //if cancel
        if (result == DialogResult.Cancel)
        {
            return;
        }

        string strFileName = fileChooser.FileName;

        try
        {
            //open file for read access
            output = new FileStream(strFileName, FileMode.Open, FileAccess.Read);

            fileReader = new StreamReader(output);

            //var to hold the read record
            string strInputLine;
            string[] fields;

            //loop to get records and break into fields
            while (fileReader.EndOfStream != true)
            {
                //read record
                strInputLine = fileReader.ReadLine();

                //split the record
                fields = strInputLine.Split(',');

                //Check for empty space
                if (!string.IsNullOrEmpty(strInputLine))
                {
                    double salaryToDouble = Convert.ToDouble(fields[3]);
                    lstBoxEmployees.Items.Add(new Employee(fields[0], fields[1], fields[2], salaryToDouble));
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //close resources
            fileReader.Close();
            output.Close();
        }
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //create dialog
        SaveFileDialog fileChooser = new SaveFileDialog();

        fileChooser.Title = "Choose a Save Location";
        fileChooser.Filter = "Text Files (*.txt)|*.txt";

        //open dialog, get result
        DialogResult result = fileChooser.ShowDialog();

        //if cancel
        if (result == DialogResult.Cancel)
        {
            return;
        }

        //get file name from dialog
        string strFileName = fileChooser.FileName;

        try
        {
            //save via filestream
            //open the new file for write access
            output = new FileStream(strFileName, FileMode.OpenOrCreate, FileAccess.Write);

            fileWriter = new StreamWriter(output);

            //take the text from listbox and write it to a file
            fileWriter.WriteLine(lstBoxEmployees);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //close resources
            fileWriter.Close();
            output.Close();
        }
    }

    private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MenuOpen();
    }

    //Properties form method.
    private void MenuOpen()
    {
        frmProperties newEmployee = new frmProperties();
        DialogResult result = newEmployee.ShowDialog();

        if (newEmployee.ShowDialog() == DialogResult.OK)
        {
            lstBoxEmployees.Items.Add(newEmployee.EmployeeNew);
        }
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        MenuOpen();
    }

    private void lstBoxEmployees_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (lstBoxEmployees.SelectedItem != null)
            if (lstBoxEmployees.SelectedItem.ToString().Length != 0)
                MenuOpen();
    }

    private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        object toRemove = lstBoxEmployees.SelectedItem;
        lstBoxEmployees.Items.Remove(toRemove);
    }
}

Custom Class:

class Employee
{
    private string firstName;
    private string lastName;
    private string empType;
    private double salary;

    //Constructor
    public Employee(string FirstName, string LastName, string EmpType, double Salary)
    {
        firstName = FirstName;
        lastName = LastName;
        empType = EmpType;
        salary = Salary;
    }

    public string EmployeeFirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public string EmployeeLastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public string EmploymentType
    {
        get { return empType; }
        set { empType = value; }
    }

    public double EmployeeSalary
    {
        get { return salary; }
        set { salary = value; }
    }

    public override string ToString()
    {
        return (firstName + ", " + lastName);
    }
}
Was it helpful?

Solution

There are a number of problems in your code.

  1. In your Form2, your btnOk_Click method puts the new employee details into a local variable (also called empVar), not the class variable. To fix this, remove the line string empVar; from the btnOk_Click method.

  2. Your lstBoxEmployees suppose to add items of type Employee, not string. So your EmployeeNew and empVar should be changed to type Employee instead of string. And your btnOk_Click method should be changed to assign the new employee to empVar directly, like this:

    empVar = testEmploy;
    
  3. Your Employee class needs to be public, as in:

    public class Employee
    
  4. Make sure your OK and Cancel buttons have their DialogResult set to OK and Cancel respectively in the Form Designer.

  5. You don't need the Close(); statement in the Cancel button event handler if you have Step 4 above done correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top