简体   繁体   中英

How to get selected combobox items and text on button when I reopen the form without using serialization 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 Connect. Connect 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 Connect 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 ask this question on stack. Somebody suggested me to use Serialization.And I used that. It was working OK. But my senior said not to use the serialization.He don't want serialization in project.

So is there any way to solve this problem? I don't know how to do this.Please help me to solve this issue. Thanks in advance.

Code for Connect 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)
   {
       if (btn_Connect.Text == "Connect")
       {
           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 == ""))
           {
               if (cb_CommPort.Text == "")
               {
                   MessageBox.Show("Please select COM Port and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               else if (cb_BaudRate.Text == "")
               {
                   MessageBox.Show("Please select BaudRate and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               else if (cb_Parity.Text == "")
               {
                   MessageBox.Show("Please select Parity and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               else if (cb_DataBits.Text == "")
               {
                   MessageBox.Show("Please select DataBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               else if(cb_StopBits.Text == "")
               {
                   MessageBox.Show("Please select StopBits and then Connect", "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";
                   cb_CommPort.Enabled = false;
                   cb_BaudRate.Enabled = false;
                   cb_DataBits.Enabled = false;
                   cb_Parity.Enabled = false;
                   cb_StopBits.Enabled = false;
                   btn_Connect.BackColor = System.Drawing.Color.Salmon;
               }

           }
       }
       else
       {
           CommPortManager.Instance.COM_Close();
           btn_Connect.Text = "Connect";
           Connect_Status = false;
           cb_CommPort.Enabled = true;
           cb_BaudRate.Enabled = true;
           cb_DataBits.Enabled = true;
           cb_Parity.Enabled = true;
           cb_StopBits.Enabled = true;
           btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
       }
   }

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

 private void Connect_Load(object sender, EventArgs e)
 {
      //code here to setup the value;
     cb_CommPort.Text = CommPortManager.Instance.PortName;
     cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
     cb_Parity.Text = CommPortManager.Instance.Parity;
     cb_StopBits.Text = CommPortManager.Instance.StopBits;
     cb_DataBits.Text = CommPortManager.Instance.DataBits;

     if (CommPortManager.Instance.IsOpen == true)
     {
         btn_Connect.Text = "Disconnect";
         btn_Connect.BackColor = System.Drawing.Color.Salmon;
         cb_CommPort.Enabled = false;
         cb_BaudRate.Enabled = false;
         cb_DataBits.Enabled = false;
         cb_Parity.Enabled = false;
         cb_StopBits.Enabled = false;
     }
     else
     {
         btn_Connect.Text = "Connect";
         Connect_Status = false;
         cb_CommPort.Enabled = true;
         cb_BaudRate.Enabled = true;
         cb_DataBits.Enabled = true;
         cb_Parity.Enabled = true;
         cb_StopBits.Enabled = true;
         btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;

     }
 }


}

And Code for main form where this connect 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";
    }
  connect.Dispose();
 }

CommPortManager Class Code :

 public class CommPortManager 
{
    //***************************************************singleton pattern
    private static CommPortManager instance;

    private CommPortManager()
    {
        ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived); // event handler
    }

    public static CommPortManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new CommPortManager();
            }
            return instance;
       }
    }

    //**************************************************************end singleton pattern

  public List<byte> Rx_Buffer = new List<byte>();

  public List<string> GetCommList()   //retrieve list of comport from Computer
   {
       return (System.IO.Ports.SerialPort.GetPortNames().ToList());
   }

  private SerialPort ComPort = new SerialPort();
    public bool COM_Open()
    {

        try
        {
            if (ComPort.IsOpen)
            {
                ComPort.Close();
            }
            ComPort.PortName = portName;
            ComPort.BaudRate = int.Parse(baudRate);  //convert Text to Integer
            ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity);    //convert Text to Parity
            ComPort.DataBits = int.Parse(dataBits);                                    //convert Text to Integer
            ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits);  //convert Text to stop bits

            ComPort.Open();

            return true;
        }
        catch (Exception)
        {

           return false;
        }
    }
    public void COM_Close()
    {
        ComPort.Close();
    }

    // declare variables for property
    private string baudRate = string.Empty;
    private string parity = string.Empty;
    private string stopBits = string.Empty;
    private string dataBits = string.Empty;
    private string portName = string.Empty;

    // Property to hold the BaudRate
    public string BaudRate
    {
        get { return baudRate;  }
        set { baudRate = value; }
    }

  // property to hold the Parity
    public string Parity
    {
        get { return parity; }
        set { parity = value; }
    }
  // property to hold the StopBits
    public string StopBits
    {
        get { return stopBits; }
        set { stopBits = value; }
    }
    // property to hold the DataBits
    public string DataBits
    {
        get { return dataBits; }
        set { dataBits = value; }
    }
    // property to hold the PortName
    public string PortName
    {
        get { return portName; }
        set { portName = value; }
    }
    public bool IsOpen { get { return ComPort.IsOpen; } }

    public bool SendData(List<byte> byte_List)
    {
        Rx_Buffer.Clear();
        try
        {
           ComPort.Write(byte_List.ToArray(), 0, byte_List.Count); //convert list data to byte array and then send to relay
            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }

     void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        int length = ComPort.BytesToRead;  //retrieve number of bytes in the buffer
        byte[] buffer = new byte[length];  //create a byte array to hold the buffer
        ComPort.Read(buffer, 0, length);   //read the data and display to the user

        Rx_Buffer.AddRange(buffer);     //Received buffer list
    }

}

When you don't want global instance of connect form and serialization you can go with following any one of way.

  1. you can use the CommPortManager.Instance to read the values on connect form load

     protected override void OnLoad(EventArgs e) { base.OnLoad(e); //code here to setup the value; cb_CommPort.Text = CommPortManager.Instance.PortName; // other fields } 
  2. You can use app.config to save and retrieve the values. Right click on Project-> settings tab add required settings(PortName, etc.,)

     protected override void OnLoad(EventArgs e) { base.OnLoad(e); //code here to setup the value; cb_CommPort.Text = Properties.Settings.Default.PortName; // other fields } private void btn_Connect_Click(object sender, EventArgs e) { Properties.Settings.Default["PortName"] = CommPortManager.Instance.PortName = cb_CommPort.Text; // your code Properties.Settings.Default.Save(); } 
  3. create custom object with single instance to store and retrieve the values

  4. Create custom object and create instance on main form and share the object between the forms. Like previous submission. check submission 1 & 2

You have to change your button Click

    private void btn_Connect_Click(object sender, EventArgs e)
    {
        if (btn_Connect.Text == "Connect")
        {
            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 == ""))
            {
                if (cb_CommPort.Text == "")
                {
                    MessageBox.Show("Please select COM Port and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (cb_BaudRate.Text == "")
                {
                    MessageBox.Show("Please select BaudRate and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (cb_Parity.Text == "")
                {
                    MessageBox.Show("Please select Parity and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (cb_DataBits.Text == "")
                {
                    MessageBox.Show("Please select DataBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (cb_StopBits.Text == "")
                {
                    MessageBox.Show("Please select StopBits and then Connect", "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
                {
                    //commenting this because when its COM_Open is success closing the Com port
                    //CommPortManager.Instance.COM_Close();
                    Connect_Status = true;
                    btn_Connect.Text = "Disconnect";
                    cb_CommPort.Enabled = false;
                    cb_BaudRate.Enabled = false;
                    cb_DataBits.Enabled = false;
                    cb_Parity.Enabled = false;
                    cb_StopBits.Enabled = false;
                    btn_Connect.BackColor = System.Drawing.Color.Salmon;
                }

            }
        }
        else
        {
            CommPortManager.Instance.COM_Close();
            btn_Connect.Text = "Connect";
            Connect_Status = false;
            cb_CommPort.Enabled = true;
            cb_BaudRate.Enabled = true;
            cb_DataBits.Enabled = true;
            cb_Parity.Enabled = true;
            cb_StopBits.Enabled = true;
            btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
        }

also form load changes as follows

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //code here to setup the value;
        cb_CommPort.Text = CommPortManager.Instance.PortName;
        cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
        cb_Parity.Text = CommPortManager.Instance.Parity;
        cb_StopBits.Text = CommPortManager.Instance.StopBits;
        cb_DataBits.Text = CommPortManager.Instance.DataBits;
        btn_Connect.Text = CommPortManager.Instance.IsOpen ? "Disconnect" : "Connect";
    }

Each time your click event is called, you are creating new instance of connect form, that's why you are losing data. Try storing connect from object as instance variable and use that instance on each click.

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