简体   繁体   中英

how call main form method inside another form using C#?

 public partial class Form1 : Form
{

    String Path1 = Application.StartupPath + "\\component.xml";
    XmlDataDocument xmlDatadoc = new XmlDataDocument();

    public Form1()
    {
        InitializeComponent();
    }

    XmlDocument dom;
    TreeNode tNode;
    const int NORM_UI = 0;
    const int SELECTED_UI = 1;

    private void Form1_Load(object sender, EventArgs e)
    {

        this.treeview();
    }

  public void treeview()
    {
        try
        {

            dom = new XmlDocument();
            dom.Load(Path1);


            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
            tNode = new TreeNode();
            tNode = treeView1.Nodes[0];
            tNode.ForeColor = Color.Blue;



            AddNode(dom.DocumentElement, tNode, NORM_UI, -1);
        }
        catch (XmlException xmlEx)
        {
            MessageBox.Show(xmlEx.Message);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

i want to call this treeview () method when button 2 click in following form please help me

 public partial class TabPageEntry_Form2 : Form
{
    public TabPageEntry_Form2()
    {
        InitializeComponent();
    }



    private void button2_Click(object sender, EventArgs e)
    {

    }

The treeview() is an instance method so you need to create an object of Form1

Form1 frm=new Form1();
frm.treeview();

I'm more familiar with asp.net. There it would simply be:

Form1.treeview();

If that is not the case, then perhaps this link may help: Calling method from another window (Class) issue

There are a couple ways. You can pass your form to your other form.

public partial class TabPageEntry_Form2 : Form
{
    Form1 form;
    public TabPageEntry_Form2(Form1 form1)
    {
        form = form1;
        InitializeComponent();
    }



    private void button2_Click(object sender, EventArgs e)
    {
        form.treeview();
    }

You can use events:

public partial class TabPageEntry_Form2 : Form
{
    public delegate void TreeViewHander();
    public event TreeViewHander TreeView;

    public TabPageEntry_Form2()
    {
        InitializeComponent();
    }



    private void button2_Click(object sender, EventArgs e)
    {
        if (TreeView) 
        {
            TreeView();
        }
    }

....

    // Form1 
    TabPageEntry_Form2 form2 = new TabPageEntry_Form2 ();
    form2.TreeView += treeview;

You just need to instantiate form1 and call the respective method;

Form1 objForm1 = new Form1();
objForm1.treeview();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM