Share via


Passing data between class and form in C#

Question

Thursday, April 6, 2006 6:57 AM

hi..
i have to pass some data from a class file to form which is having richTextBox .. any sort of help is appreciated.
                      thanks

All replies (16)

Thursday, April 6, 2006 7:46 AM ✅Answered | 1 vote

You refactor the class to it has properties:


public class Customer
{
    private string _name;

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }
}
 

Now in the Click event of a button or TextChanged event of the RithcTextBox you can set this property with the value you want:


private Customer _customer = new Customer();

private void button_Click( object sender, EventArgs e )
{
    _customer.Name = richtTextBox.Text;
}
 

Thursday, April 6, 2006 8:41 AM ✅Answered | 1 vote

If the class has a Get Property it can be done easelly, but you should not have UI logic in your classes.

You should use events for that.


public delegate void MyDelegate( object sender, string message );

public class MyClass
{
    public event MyDelegate Message;

    public void MyFunction()
    {
        // TODO: Do something.
        OnMessage( "MY DATA" );
    }

    protected void OnMessage( string message )
    {
        // If event is wired, fire it!
        if( Message != null )
        {
            // Get the target and safe cast it.
            Control target = Message.Target as Control;
           
            // If the target is an control and invoke is required,
            // invoke it; otherwise just fire it normally.
            if( target != null && target.InvokeRequired )
            {
                object[] args = new object[] { this, message };
                target.Invoike( Message,
            }
            else
            {
                Message( this, message );
            }
        }
    }
}
 

In your Form you can wire the event and when you recieve the event you append the message:



private MyClass _myClass;

private void Form_Load( object sender, EventArgs e )
{
    // Initialize member and wire event.
    _myClass = new MyClass();
    _myClass.Message += new MyDelegate(
}

private void _myClass_Message( object sender, string message )
{
    // Append the message.
    rtbox.AddendText( message );
}
 

Thursday, April 6, 2006 8:44 AM ✅Answered

Hi

Im not sure if this is gonna help.

Firstly I read data from a file in a specified format and pass it to a class it looks like


public static ArrayList GetCustomers()

            {

                  if (!Directory.Exists(dir))

                        Directory.CreateDirectory(dir);

 

                  StreamReader textIn =

                        new StreamReader(

                        new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

 

            ArrayList customers = new ArrayList();

 

                  while (textIn.Peek() != -1)

                  {

                        string row = textIn.ReadLine();

                        string[] columns = row.Split(',');

                Customer customer = new Customer();

                customer.Count = columns[0];

                        customer.LastName = columns[1];

                        customers.Add(customer);

                  }

                  textIn.Close();

 

                  return customers;

            }


My class looks like this


public Customer()

            {

            }

 

            public Customer(string lastName, string count)

            {

            this.Count = count;

            this.LastName = lastName;

            }

 

        public string Count

        {

            get

            {

                return count;

            }

            set

            {

                count = value;

            }

        }

 

            public string LastName

            {

                  get

                  {

                        return lastName;

                  }

                  set

                  {

                        lastName = value;

                  }

            }

 

        public string GetDisplayText1()

        {

            return lastName;

        }

 


The Code in my Form is


       private void ViewCode_Load(object sender, EventArgs e)

        {

            customers = CustomerDB.GetCustomers();

            FillCustomerListBox();

        }

 

        private void FillCustomerListBox()

        {

            lstCustomers.Items.Clear(); //listbox

            foreach (Customer c in customers)

            {

                lstCustomers.Items.Add(c.GetDisplayText1());

            }

        }


Hope this helps.

 


Monday, April 10, 2006 7:39 AM ✅Answered

 jmccall3 wrote:
class myClass
{
    public myClass()
    {
    }
   
    public void myFunc( )
    {
        Form1 obj=new Form1();
        obj.append_rtbox("MY DATA");
    }
}

This doesn't work because you initialize a new instance for Form1. You don't use the visable instance.

Here is the modified code from my last post, that should work.


public delegate void MyDelegate( object sender, string message );

public class MyClass
{
    public event MyDelegate Message;

    public void MyFunction()
    {
        // TODO: Do something.
        OnMessage( "MY DATA" );
    }

    protected void OnMessage( string message )
    {
        // If event is wired, fire it!
        if( Message != null )
        {
            // Get the target and safe cast it.
            Control target = Message.Target as Control;
           
            // If the target is an control and invoke is required,
            // invoke it; otherwise just fire it normally.
            if( target != null && target.InvokeRequired )
            {
                object[] args = new object[] { this, message };
                target.Invoike( Message,
            }
            else
            {
                Message( this, message );
            }
        }
    }
}
 

 

In your Form you can wire the event and when you recieve the event you append the message:

        


private MyClass _myClass;

private void Form_Load( object sender, EventArgs e )
{
    // Initialize member and wire event.
    _myClass = new MyClass();
    _myClass.Message += new MyDelegate( _myClass_Message );
}

private void _myClass_Message( object sender, string message )
{
    // Append the message.
    rtbox.AddendText( message );
}
 

Thursday, April 6, 2006 8:28 AM

thanx
       But i want to send data from a class to form which is having richtextbox.

class myClass
{
    public myClass()
   {
    }
   public void myFunc( )
  {
     Form1 obj=new Form1();
     obj.rtbox.AppendText("MY DATA");
      
 }
}

Something like this ... is this possible.


Thursday, April 6, 2006 8:40 AM

This is a bit a weird approach...
You cann pass a form as an argument to your object:
class MyClass
{
    public void MyFunc( FormWithTextBoxType theForm )
    {
            theForm.AppendTextToRichTextBox ("bliep");
    }
}

where AppendTextToRichTextBox is a public method that is defined on your form.


Saturday, April 8, 2006 7:47 PM

in your form1 put

        public void append_rtbox (string s)
        {
           rtbox.AppentText(s);
        }
then try

class myClass
{
    public myClass()
   {
    }
   public void myFunc( )
  {
     Form1 obj=new Form1();
     obj.append_rtbox("MY DATA");
      
 }
}


Sunday, April 9, 2006 12:56 PM

Hello,

I have some difficulties to use your code because some instructions aren't complete :

_myClass.Message += new MyDelegate(

and target.Invoike( Message,

I have rewritten the last one to "target.Invoke( Message);"

Can you help me in order to use your solution.

Thanks
Daniel


Monday, April 10, 2006 5:21 AM

i did that .. the data is passing from myClass to append_rtbox ..but its not appending it to richtextbox.. through debugging i can see that data is passed to that function.


Monday, April 17, 2006 10:05 PM

Does PJ van de Sande's solution work?  Isn't Message still null?


Wednesday, April 19, 2006 8:08 AM

 Charlemagne wrote:
Does PJ van de Sande's solution work? Isn't Message still null?

Only when the event isn't wired Message is null, but in the example post i have post a usage example where the event gets wired.


Tuesday, May 2, 2006 7:46 PM

I applied the logic posted by PJ van de Sande above inside a seperate class that implements a FileSystemWatcher object and had it update text on a form each time it saw a new file come in and again when it completed some processing on the file.  It worked perfectly.  Very nice.


Tuesday, May 2, 2006 8:10 PM

 Paul Deffinger wrote:
I applied the logic posted by PJ van de Sande above inside a seperate class that implements a FileSystemWatcher object and had it update text on a form each time it saw a new file come in and again when it completed some processing on the file. It worked perfectly. Very nice.

I am glad everything works perfectly! Please feel free to post whenever you have problems with implementing this!


Sunday, January 13, 2008 3:10 PM

Hi PJ, i try your solution but i want to access function between form instead class and form, everything compile correct, but my event is not fired, can you help me???

 

i use:

private form2 _myClass;

 

instead of:

private MyClass _myClass;

 

i dont really need to pass event to a control, i just need to execute function in my form1

 


Friday, June 11, 2010 9:57 PM

Hi Pieter,

 

I got the design working and it's great, however I have a slightly different sort of a conundrum.

 

I have a class in which I have the delegate and event and your structure from above example and event method working. Then I have my main UI form, MainUI from which on button click, I create a connection and instantiate my MyClass.

 

Now I have the event wired in my Form's constructor. The problem is that MyClass in my application is subscribed to some other events which i get from a COM dll source (a FIX protocol, quickfix) which sends messages and I want those messages routed to my MainUI's text display.

The function I'm calling asynchronously from my MainUI calls OnMessage method in MyClass which calls my Message event as in your example. The problem is in the dll events in that same class. For example in MyClass I have an event method like this:  

public
 MyClass { <br/>





...<br/>





public
 void
 toAdmin(Message message, SessionID sessionId) {

 Message("toAdmin: "
 + sessionId);

 crack(message, sessionId);

 }<br/>





}

So as you can tell I'm simply trying to send the toAdmin: "sessionId" string to my MainUI's message box. However when I try to do this I get a NullReferenceException and the debugger shows the event is null. Any ideas why it doesn't work in event method but works in my own method I call from MainUI?? Perhaps toAdmin looses the reference to the current form? Please help.


Thursday, May 19, 2011 11:21 AM

Hi bulldog!

I am using i really similar code as you for an assignment but I am getting error in a line when running it... it passes trough compile without errors..

        public void RestoreVideoFromTxtFile()
        {
            string dir = @"C:\C#\Files\;
            string path = dir + "Videos.txt";

            // create the object for the input stream for a text file
            StreamReader textIn = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

            // read the data from the file and store it in the list
            while (textIn.Peek() != -1) this line gives me the error under the method
            {
                string row = textIn.ReadLine();
                string[] columns = row.Split('|');
                Video temp = new Video();
                temp.artNr = int.Parse(columns[0]);
                temp.title = columns[1];
                temp.year = int.Parse(columns[2]);
                video.Add(temp);

                // close the input stream for the text file
                textIn.Close();
            }

     }

ERROR:

System.ObjectDisposedException was unhandled
  Message=Cannot read from a closed TextReader.
  Source=mscorlib
  ObjectName=""
  StackTrace:
       at System.IO.__Error.ReaderClosed()
       at System.IO.StreamReader.Peek()
       at Videostore_lab4.Videostore.RestoreVideoFromTxtFile() in Q:\ID132V-C#-programmering\Lab\lab4\VideoStore_Lab4\VideoStore_Lab4\Videostore.cs:line 345
       at Videostore_lab4.Videostore.RunVideostore() in Q:\ID132V-C#-programmering\Lab\lab4\VideoStore_Lab4\VideoStore_Lab4\Videostore.cs:line 89
       at Videostore_lab4.Videostore.Main(String[] args) in Q:\ID132V-C#-programmering\Lab\lab4\VideoStore_Lab4\VideoStore_Lab4\Videostore.cs:line 112
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: