user1527484
user1527484

Reputation: 67

c# SerialPort access between multiple forms

I have two forms. Form1 and Form2. SerialPort variable is declared in Form1.cs

    public SerialPort COM = null;

    public SerialPort GetCOMM
    {
        get { return COM; }
    }

I need to access that variable from Form2. (Form1 creates Form2)
Have tried access to seriarialport these ways

Form1 f1 = new Form1();
int result = myfunction(f1.GETCOMM);
int result = myfunction(f1.COM);

and it's not working. what I'm doing wrong?

Upvotes: 0

Views: 6944

Answers (2)

Wanabrutbeer
Wanabrutbeer

Reputation: 697

If both forms are part of same app, you can place a static SerialPort object in your Program.cs class. Then call it from anywhere by Program.SerialPort

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

I would personally create a Method on Form2 that takes a SerialPort as a Parameter, that way it does not have to have a reference to Form1. I would do something like this. Or you can create a Custom Constructor like jaminator commented for Form2 that Receives the SerialPort as a Parameter

Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.setSerialPort(serialPort1);
        frm2.Show();
    }
}

Form2

public partial class Form2 : Form
{
    SerialPort myPort;
    public Form2()
    {
        InitializeComponent();
    }
    public void setSerialPort(SerialPort port)
    {
        myPort = port; 
    }
}

Second Option with custom Constructor

Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2(serialPort1);
        frm2.Show();
    }
}

Form2

public partial class Form2 : Form
{
    SerialPort myPort;
    public Form2( SerialPort port)
    {
        InitializeComponent();
        myPort = port; 
    }
}

Upvotes: 4

Related Questions