【问题标题】:Populate a gridform from another Class从另一个类填充网格表格
【发布时间】:2018-07-26 18:18:59
【问题描述】:

这个问题类似于:

-How to change a label from another class? c# windows forms visual 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();要运行的方法?

【问题讨论】:

  • hmmm...尝试在 InsertNode 时设置 dataGridViewNodes.DataSource = null ..
  • 感谢 muhammadaa 的建议,但这并没有什么不同。
  • 为了我自己的学习,如果有人能告诉我为什么我的问题被标记了,我将不胜感激。我看不出这个问题有任何明显的问题,或者我是如何写的?谢谢

标签: c# winforms class datagrid


【解决方案1】:

这里的问题是您正在创建一个新的 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 列表中查找表类型的表单。如果有,它将获得对它的引用并调用 UpdateNodeForm()。如果它不存在,那么它什么也不做。

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

using System.Windows.Forms;

【讨论】:

  • 这很好,谢谢。我没有意识到“Application.OpenForms”甚至存在(对 C# 来说非常新),所以感谢您开辟了新的可能性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 2019-09-29
相关资源
最近更新 更多