Как получить выбранные элементы комбинированного списка и текст на кнопке при повторном открытии формы без использования сериализации в C # - PullRequest
0 голосов
/ 04 июня 2018

Я создал проект в приложении формы C # windows в Visual Studio 2010 и .net Framework версии 4.0.

В моем проекте главная форма содержит другую форму с именем Connect.Форма подключения имеет пять полей со списком для настроек COM-порта и кнопку подключения.Когда я выбираю элементы из выпадающего списка в поле со списком и нажимаю кнопку подключения, текст на кнопке показывает отключение.Затем я закрою форму подключения. Comport подключается.

Моя главная проблема заключается в том, что при повторном открытии формы для отключения связи.Я хочу, чтобы в поле со списком были те же элементы, а текст на кнопке показывает «Отключение», как и раньше.

Я задаю этот вопрос в стеке.Кто-то предложил мне использовать сериализацию. И я использовал это.Это работало хорошо.Но мой старший сказал не использовать сериализацию. Он не хочет сериализации в проекте.

Так есть ли способ решить эту проблему?Я не знаю, как это сделать. Пожалуйста, помогите мне решить эту проблему.Заранее спасибо.

Код для формы подключения

  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;

     }
 }


}

И код для основной формы, где открыта эта форма подключения

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:

 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
    }

}

Ответы [ 2 ]

0 голосов
/ 04 июня 2018

Если вам не нужен глобальный экземпляр формы подключения и сериализации, вы можете воспользоваться любым из следующих способов.

  1. вы можете использовать CommPortManager.Экземпляр для чтения значений при загрузке формы подключения

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //code here to setup the value;
        cb_CommPort.Text = CommPortManager.Instance.PortName;
        // other fields
    }
    
  2. Вы можете использовать app.config для сохранения и получения значений.Щелкните правой кнопкой мыши на Project-> вкладка настройки и добавьте необходимые параметры (имя_порта и т.*

  3. Создайте пользовательский объект и создайте экземпляр в главной форме и поделите объект между формами.Как и предыдущая подача.проверить отправку 1 & 2

Вы должны изменить свою кнопку. Нажмите

    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;
        }

, также сформируйте изменения нагрузки следующим образом

    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";
    }
0 голосов
/ 04 июня 2018

Каждый раз, когда вызывается событие click, вы создаете новый экземпляр формы подключения, поэтому теряете данные.Попробуйте сохранить соединение из объекта в качестве переменной экземпляра и использовать этот экземпляр при каждом щелчке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...