Nyra
Nyra

Reputation: 897

Accessing Form object from different class

I am trying to access a Form's RichTextBox control via a separate class.

In my form class...

    delegate void SetTextCall(string s);

    public void safeCall(string s)
    {
        if (this.richTextBox1.InvokeRequired)
        {
            SetTextCall d = new SetTextCall(safeCall);
            this.Invoke(d, new object[] { s });
        }
        else this.richTextBox1.AppendText("From Applicator");
    }

In a different class...

public void getMessages()
    {
        lock (lockObj)
        {
            Dictionary<string, List<string>> result = ScannerMessages
                .GroupBy(k => k.Value)
                .Where(grp => grp.Count() > 1)
                .ToDictionary(grp => grp.First().Key, grp => grp.Skip(1).Select(k => k.Key).ToList());

            if(result.Count > 0)
            {
                foreach(var key in result.Keys)
                {
                    // I want to write to the rich textbox the key and the list accosiated with the key 
                    // in the richtextbox on Form1
                }
             }
        }
    }

I have tried modifying the textbox to be public, and I tried tinkering with making a static method to call. I am not sure how to go about this.

Upvotes: 0

Views: 110

Answers (1)

Servy
Servy

Reputation: 203825

You should keep your UI separate from your business logic. This means that this class, which is performing a computation on some data, should know nothing at all about your UI, and should not know anything about a form or its contents.

Instead it should simply return the value, instead of having the method be void. Then your UI can call this method, get the result, and then handle displaying that result however it feels it is necessary.

In addition to being easier, it greatly reduces coupling. It prevents this class from being tied to just this one UI, and it allows the UI and business logic to be developed independently, without requiring either to have an intimate knowledge of the other. This makes development easier, and it makes the program much easier to reason about, improving maintainability, easing debugging, etc.

Upvotes: 2

Related Questions