繁体   English   中英

如何在C#中使用另一种Form(或另一类的一个类)中的方法

[英]How to use a method from one Form in another (or one class in another class) in C#

因此,我在Form2中有一个树形视图。 在按钮上单击,在Form3中执行代码,将文本框(来自Form3)中的文本插入数据库中,然后,我希望Form2中的树形视图使用数据库中的值更新自身,这意味着我需要在我在Form3中编写的代码中使用treeView1(来自Form2),或者在Form2中编写一个方法(已完成)以在Form3中使用。

Form2中的方法:

    public static void LoadTree()
    {
        int j = 1;
        string var;
        con.Open();
        OleDbCommand populate = new OleDbCommand("SELECT Project_name FROM Edit_Nodes ORDER BY Location ASC", con);
        OleDbDataReader reader = populate.ExecuteReader();
        while (reader.Read())
        {
            var = "H" + j + " - " + reader["Project_name"] + "";
            treeView1.Nodes[j].Text = var;
            j++;
        }
        con.Close();
    }

问题:“错误5非静态字段,方法或属性'Tool.Form2.con'需要一个对象引用”,依此类推,treeView1和代码中的其他con都是如此。

Form3中的代码:

   private void button1_Click(object sender, EventArgs e)
    {
       // more code here

      Form2.LoadTree();
    }

我的问题是如何解决这些错误,或者....如何直接使程序识别Form3(属于Form2)中的treeView1,以便在那里再次编写代码。

首先,使其成为实例方法而不是静态方法:

public void LoadTree()
{
    // implementation
}

static不起作用的原因是因为它没有任何给定实例形式的上下文,因此它没有任何给定实例上控件的上下文(例如treeView1 )。 接下来,您将需要Form3实例具有对该特定Form2实例的引用。 一种简单的方法是在Form3添加一个属性,并在其构造函数中需要引用。 因此,在Form3

private Form2 Form2Instance { get; set; }

public Form3(Form2 form2Instance)
{
    this.Form2Instance = form2Instance;
}

此时,无论Form3需要创建Form3的实例,都需要为其提供Form2的实例。 因此,如果您在Form2创建它,则可以执行以下操作:

var form3Instance = new Form3(this);
form3Instance.Show();

那时,任何Form3实例都引用了创建它的Form2实例。 因此, Form3上的代码可以仅引用该私有属性中的实例来调用该方法:

private void button1_Click(object sender, EventArgs e)
{
    // more code here
    this.Form2Instance.LoadTree();
}

您的代码有很多问题,请参阅我的评论

  // Since you want to update treeView1 you should 
  // point out on which instance of Form1 the target treeView1 is.
  // That's why LoadTree() can't be static
  public void LoadTree() { // <- Not static!
    // Much better to use a local connection here
    //TODO: provide the right connection string here
    using(OleDbConnection con = new OleDbConnection(connectionString)) {
      con.Open();

      // wrap all local IDisposable into using(...) {...}
      using (OleDbCommand populate = new OleDbCommand(con)) {
        // Format out your SQL for it to be readble
        populate.CommandText = 
          "  select Project_Name\n" + 
          "    from Edit_Nodes\n" +
          "order by Location asc";

        // wrap all local IDisposable into using(...) {...}
        using (OleDbDataReader reader = populate.ExecuteReader()) {
          // When updating visual controls prevent them from constant re-painting
          // and annoying blinking
          treeView1.BeginUpdate();

          try {  
            // What is "j"? No-one knows; "loop" is more readable
            int loop = 1;

            while(reader.Read()) {
              // "var" is unreadable, "nodeText" is clear
              String nodeText = "H" + loop.ToString() + " - " + reader["Project_Name"];

              // Check ranges: what if SQL returns more recods than treeView1's nodes? 
              if (loop >= treeView1.Nodes.Count) 
                break;

              treeView1.Nodes[loop].Text = nodeText;

              loop += 1;
            }
          finally {
            treeView1.EndUpdate();
          }  
        }  
      }
    }

现在,该调用LoadTree() 但是对于哪个 Form2实例? 想象一下,您已经打开了五个 Form2 现在让我们为所有Form2实例调用LoadTree()

private void button1_Click(object sender, EventArgs e) {
  // Enumerating all open forms
  foreach (Form form in Application.OpenForms) {
    Form2 source = form as Form2;

    // If the open form is Form2, call LoadTree
    if (!Object.ReferenceEquals(null, source))
      source.LoadTree();
  }
}

看起来您对LoadTree()方法中名为“ treeView1”的操作。 如果这是Form2的一部分,则它必须是静态的,或者您必须从已实例化的对象中调用此方法。

  1. 使treeView1静态
  2. Form2形式=新的Form2(); form.TreeView();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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