0

I am working with serialport. I have two window forms and I need to use the serialPort in both forms. How can I send serialport from one form to the 2nd one as a parameter? My code looks like:

namespace SimpleSerial
{
  public partial class Form1 : Form
  {
    Form2 pp = new Form2()

      public Form1()
      {
        InitializeComponent();
        pp.ShowDialog();
      }
      private void buttonStart_Click(object sender, EventArgs e)
      {
        serialPort1.PortName = "Com3";       
        serialPort1.BaudRate = 9600;

and code for 2nd Form:

namespace SimpleSerial
{
  public partial class Form2 : Form
    {
      public Form2()
        {
          InitializeComponent();
          getAvailablePorts();
        }
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
user6203007
  • 33
  • 1
  • 1
  • 8
  • You havent shown your serial variable, you can have it as a property on form2, that you can pick up from form1, or, have form1 subscribe to a "selected" event .. choice is yours see https://social.msdn.microsoft.com/Forums/vstudio/en-US/d7e9f80c-5144-4ad9-aa5e-7803363ae0cd/passing-variables-between-forms?forum=csharpgeneral – BugFinder May 17 '16 at 08:20
  • Thanks . Now I have updated my question. you can see the serial variable – user6203007 May 17 '16 at 08:24
  • that code is not viable - my URL link still stands as the answer – BugFinder May 17 '16 at 08:27
  • Possible duplicate of [Passing variable between winforms](http://stackoverflow.com/questions/4247807/passing-variable-between-winforms) – Sinatr May 17 '16 at 08:31

2 Answers2

0

Pass the Port through the constructor of your Form2:

public partial class Form2 : Form
{
  private readonly SerialPort Port;
  public Form2(SerialPort Port)
  {
    InitializeComponent();
    this.Port = Port;
  }
}

Now you are able to use the Port in your Form2.

During creation of the Form2 in your Form1, pass the Port like this:

public partial class Form1 : Form
{
  private SerialPort Port;
  public Form1()
  {
    InitializeComponent();
    Port = new SerialPort();
    Form2 pp = new Form2(Port);
    pp.ShowDialog();
  }
}

Note that objects are passed by reference in C#. That means, if you close the Port in Form1 for example, the Port in Form2 is also closed (because its the same object)!

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
0

first create parameterized constructor in form2 as

public Form2(SerialPort SP)
{
     InitializeComponent();
     serialPort2 = SP;
}

now pass SerialPort from form1 to form2 as

Form2 frm = new Form2(serialPort1);
frm.ShowDialog();

so on form2 serialPort2 will get all the properties of form1 serialPort1

Pranav Patel
  • 1,541
  • 14
  • 28