如何使用C#在另一个表单内调用main form方法?

时间:2011-09-07 04:23:20

标签: 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);
        }

    }

我想在按钮2点击下面的表格时调用这个treeview()方法请帮帮我

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



    private void button2_Click(object sender, EventArgs e)
    {

    }

4 个答案:

答案 0 :(得分:1)

treeview()是一个实例方法,因此您需要创建Form1

的对象
Form1 frm=new Form1();
frm.treeview();

答案 1 :(得分:0)

我对asp.net比较熟悉。它只会是:

Form1.treeview();

如果情况并非如此,那么这个链接可能有所帮助:Calling method from another window (Class) issue

答案 2 :(得分:0)

有几种方法。您可以将表单传递给其他表单。

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();
    }

您可以使用活动:

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;

答案 3 :(得分:0)

您只需要实例化form1并调用相应的方法;

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