Passing data between class and form in C# using delegate parameter

谁都会走 提交于 2020-01-25 07:46:11

问题


I have to pass value into RichTextBox from a class. Here is my code. I have to pass values into any tools like textbox, listbox but I don't know how. I have to use delegates to pass md value to both methods and into the same richtextbox.


 namespace delegateEx2
{
    public class MyClass : Form1
    {
        delegate void MyDelegate(string MyString);

        public void ShowThoseMessages()
        {
            MyDelegate md = new MyDelegate(log1);
            md += log2;
            md("Error Log Text");
        }

        public void log1(string message) {

            //what can I write here to pass the md into the RichTextBox on Form1.cs
            //I tried something like Systems.Windows.Form.rtxblog but did not work 
            //......................................


        }

        public void log2(string message2)
        {

          //.....................................

        }

    }


回答1:


The simple questions is to change the modifier in your richtextbox declaration. You can find the declaration in Form1.designer.cs. Change the modifier from private to protected, then you can access the richtextbox from log1 method.




回答2:


I had to look this up before. Here is some example code...

TheClass.cs

using System.Windows.Forms;

...

public bool validateForm(TextBox txtTitle, TextBox txtPath, CheckedListBox ckList)
{
    bool title = false;
    bool path = false;

    if (txtTitle.Text == String.Empty)
    {
       title = false;
       txtTitle.Text = "Title is empty!";
       paintred(txtTitle);
    } else { title = true; paintwhite(txtTitle); }
    if (txtPath.Text == String.Empty)
    {
       path = false;
       txtPath.Text = "Path is empty!";
       paintred(txtPath); 
    } else { path = true; paintwhite(txtPath); }   

    bool ckItem1 = ckList.GetItemChecked(0);
    bool ckItem2 = ckList.GetItemChecked(1);
    bool ckItem3 = ckList.GetItemChecked(2);
    bool ckItem4 = ckList.GetItemChecked(3);
    bool ckItem5 = ckList.GetItemChecked(4);

    if (title && path && ckItem1 && ckItem2 
        && ckItem3 && ckItem4 &&
           ckItem5 )
        return true;
    else
        return false;
}

Then in my form I have...

    if (TheClass.validateForm(txtBox, txtBox2, listCheckList))
    {
        txtBox3.Text = TheClass.generateItem1(something, something2);
        txtBox4.Text = TheClass.generateItem2(something, something2, txtPath.Text, txtTitle.Text, listCheckList.GetItemChecked(5));
    }
    else
    {
        MessageBox.Show("Please check fields marked in red, if any. Double check your Check List required items.", "Title Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }


来源:https://stackoverflow.com/questions/14494604/passing-data-between-class-and-form-in-c-sharp-using-delegate-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!