0

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.

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?

My refresh button code:

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

1 回答 1

2

首先,将您的刷新代码包装到它自己的方法中,并从您的单击事件处理程序方法中调用它,如下所示:

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

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

然后,假设您正在从 Form1 实例化并启动新表单 (Form2),只需进入 Form2 的代码并为自己创建一个新的构造函数重载,它将接受对 Form1 的引用,并将其存储在私有变量中,就像这样:

public partial class Form2 : Form
{
    private Form1 frm1;

    public Form2()
    {
        InitializeComponent();
    }

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

然后,您可以从 Form2 中任何您喜欢的地方调用“刷新”,如下所示:

this.frm1.RefreshData();


编辑:

我创建了一个小示例,我无法在此处上传...但这是 VS 中程序本身的屏幕截图,以及运行它和执行功能的结果的屏幕截图...希望这会帮助。

程序(如果它看起来太小,请缩放您的视图) VS 2010 中的程序


结果: Form1 上的一个函数,从 Form2 调用

于 2012-09-18T02:44:58.037 回答