在C#中从另一个表单调用一个方法 [英] Calling a method from another Form in C#

查看:206
本文介绍了在C#中从另一个表单调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以另一种形式( Form2 )插入或更新记录时,我希望 DataGridView Form1 应该在每个操作之后自动刷新(调用 btnRefresh ),或者最好等待所有更改操作都有完成,并更新$ code> DataGridView 表单 Form2 的关闭事件与所有更改。

I want that when I insert or update records in another form (Form2), the DataGridView on Form1 should automatically refresh (call btnRefresh) after each operation or preferably wait until all change operations have finished, and update the DataGridView form Form2's closing event with all changes.

我相信VB.NET这是通过 Form1.DataGridView.Refresh 实现的,但我不确定C#。我被告知,我将 DataGridView 的引用传递到 Form1 Form2 使用属性,但由于我是C#的新手,我不知道如何。我如何解决这个问题?

I believe in VB.NET this is achieved with Form1.DataGridView.Refresh, but I am not sure in C#. I was told that I pass the reference of the DataGridView on Form1 to Form2 using properties but since I'm new to C#, I didn't know how to. How can I resolve this issue?

我的刷新按钮代码:

private void btnRefresh_Click(object sender, EventArgs e)
{
    GVThesis.DataSource = thesisRepository.GetThesis();
    GVThesis.Refresh();
}


推荐答案

转换成自己的方法,并从您的点击事件处理程序方法中调用该方法,如下所示:

Firs, wrap your refresh code into a method of its own, and call that from your click event handler method, like so:

    private void btnRefresh_Click(object sender, EventArgs e) 
    { 
        this.RefreshData();
    }

    public void RefreshData()
    {
        GVThesis.DataSource = thesisRepository.GetThesis(); 
        GVThesis.Refresh(); 
    }

然后,您正在从您的实例化和启动新表单(Form2) Form1,只需进入Form2的代码,并创建一个新的构造函数重载,它将接受对Form1的引用,并将其存储在私有变量中,如下所示:

Then, asuming you are instantiating and launching the new form (Form2) from your Form1, simply go into the code of Form2 and create yourself a new constructor overload which will accept a reference to Form1, and store it in a private variable, like so:

public partial class Form2 : Form
{
    private Form1 frm1;

    public Form2()
    {
        InitializeComponent();
    }

    public Form2(Form1 otherForm)
    {
        InitializeComponent();
        this.frm1 = otherForm;
    }
}

然后你可以从任何地方调用刷新像Form2一样如此:

Then you can call the "refresh" from anywhere you like in Form2 like so:

this.frm1.RefreshData();


编辑:

我创建了一个小样本,我无法在这里上传...但这里是VS中的程序本身的截图,以及运行它并执行该功能的结果的屏幕截图...希望这将有所帮助。


该程序(缩放你的视图,如果它看起来太小)




I created a small sample, I cannot upload it here...but here is a screenshot of both the program itself in VS, as well as a screenshot of the result of running it and performing the function...hopefully that will help.

The program (zoom your view if it appears too small)


结果:


The Result:

这篇关于在C#中从另一个表单调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆