首页 > 解决方案 > 从另一个类填充网格表格

问题描述

这个问题类似于:

-如何更改另一个类的标签?时间:2019-05-10 标签:c#windowsformsvisual studio

但是,我在那里没有找到合适的答案:

当调用另一个类的方法时,我想请求更新网格表单。

到目前为止,我在与表单相同的公共部分类中拥有它(按钮是临时的)。

private void button1_Click(object sender, EventArgs e)
{
    UpdateNodeForm();
}

public void UpdateNodeForm()
{
    Debug.WriteLine("-----message recieved to update tables-----");
    DataTable nodeTable = new DataTable();
    nodeTable = SqlConnections.GetNodeTableData();
    dataGridViewNodes.DataSource = nodeTable.DefaultView;
}

当我单击按钮时,上面的代码工作得很好。

但是,当我从另一个公共静态类运行以下命令时,会在新实例中调用该方法,但它不会更新表单(表单类称为 Tables)。

public static void InsertNode(string node_name, float x, float y, float z_cover)
{        
    //bunch of other stuff here that I've stripped out.

    Tables tables = new Tables();
    Debug.WriteLine("-----send instruction to rebuilt nodes tables-----");
    tables.UpdateNodeForm();
}

以上显然不是我应该这样做的方式。我怎样才能使方法 UpdateNodeForm(); 监听 InsertNode(); 要运行的方法?

标签: c#winformsclassdatagrid

解决方案


这里的问题是您正在创建一个新的 Tables 实例并在其上调用 UpdateNodeForm。

public static void InsertNode(string node_name, float x, float y, float z_cover)
{
    Tables tables = new Tables(); // This creates a new instance of Tables
    tables.UpdateNodeForm(); // This updates the new instance of Tables
}

您需要获取对原始“表格”表格的引用并在其上调用 UpdateNodeForm,或者如果您只拥有一个表格表格,那么您可以更新您的静态 InsertNode 函数以查找现有表格并更新它。

public static void InsertNode(string node_name, float x, float y, float z_cover)
{
    Tables tables = Application.OpenForms.OfType<Tables>().FirstOrDefault();
    if (tables != null)
        tables.UpdateNodeForm();
}

这将在 Application.OpenForms 列表中查找类型为 Tables 的表单。如果有,它将获得对它的引用并调用 UpdateNodeForm()。如果它不存在,那么它什么也不做。

编辑:确保您使用的是以下命名空间:

using System.Windows.Forms;

推荐阅读