TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
hello leong
NA
13
6.2k
How can I call Serial Port declare in Main Form from a class
Mar 10 2011 7:47 AM
I can call serial port in main from by clicking the button 1.
[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
disconnectBtn.Enabled = true;
connectBtn.Enabled = false;
}
catch
{
MessageBox.Show("Error", "Unable To Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (connectBtn.Enabled == false)
{
textBox1.Text = "Connected";
}
}
private void disconnectBtn_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
connectBtn.Enabled = true;
disconnectBtn.Enabled = false;
}
catch
{
MessageBox.Show("Error", "Unable To Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (disconnectBtn.Enabled == false)
{
textBox1.Text = "Disconnected";
}
}
private void button1_Click_1(object sender, EventArgs e)
{
serialPort1.Write(new byte[] {0x55}, 0, 1); //OK
}
private void button2_Click(object sender, EventArgs e)
{
Class1 sp = new Class1();
sp.serialOut();
}
}
}
[/code]
But, when i click button2 link to class2 to call serial port, it does not work.
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
class Class1
{
public void serialOut()
{
MainForm _mainForm = new MainForm();
_mainForm.serialPort1.Open(); //UnauthorizedAccessException was unhandle
_mainForm.serialPort1.Write(new byte[] { 0x55 }, 0, 1); //InvalidOperationException was unhandle
}
}
}
[/code]
I had set the serialPort1 to public in properties.
How can i solve this? Thank you.
Reply
Answers (
15
)
Abstract Class
Select query without identy column