c# - 从另一个类填充网格表格
问题描述
这个问题类似于:
-如何更改另一个类的标签?时间: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(); 要运行的方法?
解决方案
这里的问题是您正在创建一个新的 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;
推荐阅读
- bash - 带有for循环的ansible剧本没有按预期工作
- string - 在Java 8+中将数字的字符串表示形式转换为整数(没有if的单行)
- sentinel - ServiceStack.Redis:没有可用的 Redis 哨兵
- php - 无法将邮件发送到 Gmail dsn=5.0.0,stat=服务不可用
- python - 使用 *args 和 **kwargs 而不是显式列出预期参数
- java - 用 Java 解析嵌套的 JSONArrays
- c# - 如何使用 NewtonSoft JSON.Net Serialize() 去除 JSON 文件属性名中的引号?
- c# - 如何在现有 MVC 应用程序中在特定路径启用 Spa 中间件
- ios - RxSwift:在子视图控制器中从 TableViewCell 观察 UITextFields
- django-rest-framework - DRF docs - 动态获取序列化程序