Hi all c#corner forums,
I'm trying to create my class, but I couldn't succeed to work this code. When I run program, newSerial.sendData() in the Form1.Load() (this is my function which is in my own class) works perfectly, but when I clicked the button (you can see the code, I'm calling the same function) program throws "NullReferenceException" error. What is the solution?
[CODE]
namespace robitSeri
{
public partial class Form1 : Form
{
public mySerial newSerial;
private void Form1_Load(object sender, EventArgs e) { mySerial newSerial = new mySerial(this); newSerial.sendData();
// THIS WORKS EXCELLENTLY..
}
private void button1_Click(object sender, EventArgs e)
{
newSerial.sendData();
// THIS CODE DOES NOT WORK!!!
}
// this is original class which is automatically created when
// I create new Windows Form application
// And I can control everything when I'm coding in this class
}
public class mySerial // this class created by me
{
private Form1 frm;
public mySerial(Form1 newFrm)
{
this.frm=newFrm;
}
public void sendData()
{
frm.serialPort1.Write(sth);
}
// I can't reach Form1 controls from this class.
}
[/CODE]
Loading
ben senPosted Aug 28, 2011, 9:18 AM
Gomathi PalaniswamyPosted Aug 28, 2011, 9:02 AM
check the below code...and what is "frm.serialPort1.Write(sth);"
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;
namespace Forum_Q
{
public partial class Form1 : Form
{
mySerial newSerial;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
newSerial = new mySerial(this);
newSerial.sendData();
}
private void button1_Click_1(object sender, EventArgs e)
{
newSerial = new mySerial(this);
newSerial.sendData();
// THIS CODE DOES NOT WORK!!!
}
}
public class mySerial // this class created by me
{
private Form1 frm;
public mySerial(Form1 newFrm)
{
this.frm=newFrm;
}
public void sendData()
{
frm.serialPort1.Write(sth);
}
// I can't reach Form1 controls from this class.
}
}
Amit ChoudharyPosted Aug 28, 2011, 8:59 AM
ra change the signature of function remove the code from the class mySerial constructor.
public void sendData(Form1 prntForm)
{
prntForm.serialPort1.Write(sth);
}
If should work. Try it.
VulpesPosted Aug 28, 2011, 8:58 AM