简体   繁体   中英

How to get selected combobox items and text on button when I reopen the form in C#

I created a project in C# windows form application in visual studio 2010 and .net framework version 4.0.

In my project Main form contains another form which name is Communication . Communication form has five combo box for COM Port settings and Connect button. When I select Items from Combo box drop down list and click on connect button then text on button shows disconnect. Then I will close Communication form.Comport gets connected.

My main problem is that, when I reopen form for disconnect communication. I want same Items in combo box and text on button shows Disconnect as before.

I don't know how to do this. Please help me to solve this issue. Thanks in advance.

Code for Communication form

 public partial class Connect : Form
{
    public bool Connect_Status = false;

    public Connect()
    {
       InitializeComponent();
        COM_List();

    }
   private void COM_List()
    {
        for (int i = 0; i < CommPortManager.Instance.GetCommList().Count; i++)
        {
            cb_CommPort.Items.Add(CommPortManager.Instance.GetCommList()[i]);
        }
    }

  private void btn_Connect_Click(object sender, EventArgs e)
    {
        CommPortManager.Instance.PortName = cb_CommPort.Text;
        CommPortManager.Instance.BaudRate = cb_BaudRate.Text;
        CommPortManager.Instance.Parity = cb_Parity.Text;
        CommPortManager.Instance.StopBits = cb_StopBits.Text;
        CommPortManager.Instance.DataBits = cb_DataBits.Text;

        if ((cb_CommPort.Text == "") || (cb_BaudRate.Text == "") || (cb_Parity.Text == "") || (cb_DataBits.Text == "") || (cb_StopBits.Text == ""))
        {
            MessageBox.Show("Please select all communication settings and then Save", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Connect_Status = false;
        }
        else
        {
            if (CommPortManager.Instance.COM_Open() == false)
            {
                MessageBox.Show("Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Connect_Status = false;
            }
            else
            {
                CommPortManager.Instance.COM_Close();
                Connect_Status = true;
                btn_Connect.Text = "Disconnect";

            }

        }
    }

 private void btn_Close_Click(object sender, EventArgs e)
    {
        this.Close();
    }
 }
}

And Code for main form where this communication form open

 private void connectToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Connect connect = new Connect();
        connect.ShowDialog();
        if (connect.Connect_Status == true)
        {
            lb_Comm.Text = String.Format("Connected to '{0}'", connect.cb_CommPort.SelectedItem);
        }
        else
        {
            CommPortManager.Instance.COM_Close();
            lb_Comm.Text = "Not Connected";
        }
  }

You have to create a Serializable class in which you will be saving the indexes of combo boxes.

[Serializable]
class SaveComboSettings
{
    [OptionalField]
    public int cmb1SelectedIndex = 0;

    [OptionalField]
    public int cmb2SelectedIndex = 0;
}

At the time of closing the form , You need to serialize the combo boxes's index in this class's object. Like -

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    //Assigning the current selected index of combobox to serialize class.
    SaveComboSettings f1 = new SaveComboSettings();
    f1.cmb1SelectedIndex = this.comboBox1.SelectedIndex;
    f1.cmb2SelectedIndex = this.comboBox2.SelectedIndex;

    //Serialize
    BinaryFormatter bf = new BinaryFormatter();
    FileStream fsout = new FileStream("ComboBoxSettings.binary", FileMode.Create, FileAccess.Write, FileShare.None);
    try
    {
        using (fsout)
        {
            bf.Serialize(fsout, f1);                   
        }
    }
    catch (Exception Ex)
    {
        //Some Exception occured
    }  
}

When form is loaded back/restart, You need to deserialize the settings and assign the combo box values back -

public Form1()
{
    InitializeComponent();

    DeserializeFormSettings();

}

public void DeserializeFormSettings()
{          
    BinaryFormatter bf = new BinaryFormatter();
     FileStream fsin;

    if(File.Exists("ComboBoxSettings.binary"))
        fsin = new FileStream("ComboBoxSettings.binary", FileMode.Open, FileAccess.Read, FileShare.None);
    else
        return;
    try
    {
        using (fsin)
        {
            SaveComboSettings f1 = (SaveComboSettings)bf.Deserialize(fsin);
            this.comboBox1.SelectedIndex = f1.cmb1SelectedIndex;
            this.comboBox2.SelectedIndex = f1.cmb2SelectedIndex;
        }
    }
    catch(Exception Ex)
    {
        // "An error has occured";  
    }
}

This example is created with combo box only. You can use the same way for string on button also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM