【问题标题】:One form closed - second updates the DataGridView一个表单关闭 - 第二个更新 DataGridView
【发布时间】:2014-03-19 20:07:57
【问题描述】:

在 C# 上编写应用程序。 我用一个按钮打开了 Form1,通过单击调用打开 Form2。 我想做以下事情:当我关闭 Form2 时,我希望作为 Form1 的一个元素的 DataGridView 刷新自己。 问题不在于如何更新网格。 问题是如何创建一个方法来通知 Form1 Form2 已关闭。 提前致谢! 那是 Form2 的代码。在这种情况下,不需要 Form1 的代码。

using System;`
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace cSharp_App
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

    public void button1_Click(object sender, EventArgs e)
    {
        string myConnection = Form1.myConnection;
        string qry = "insert into pst.students_info (lastname,firstname,username,password,email) values ('" + this.lastname_txt.Text + "','" + this.firstname_txt.Text + "','" + this.username_txt.Text + "','" + this.password_txt.Text + "','" + this.email_txt.Text + "') ;";
        MySqlConnection myConn = new MySqlConnection(myConnection);
        MySqlCommand cmdInsert = new MySqlCommand(qry, myConn);
        MySqlDataReader myReader;
        try
        {
            myConn.Open();
            myReader = cmdInsert.ExecuteReader();
            MessageBox.Show("Пользователь добавлен");
            while (myReader.Read())
            {

            }
        }
        catch (MySqlException ex) {
            MessageBox.Show(ex.Message);

        }

    }



}

}`

【问题讨论】:

  • 已经有一个方法可以通知表单的关闭(准确地说是两个)。您需要做的就是从 Form1 中捕获该事件

标签: c# winforms forms


【解决方案1】:

当您在Form1 中打开Form2FormClosed 事件时,您应该订阅它。

Form frm = new Form2();
frm.FormClosed += Form2_FormClosed;
frm.Show();

并在处理程序中刷新网格:

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
    // refresh the gridview
}

【讨论】:

  • 第一段应该写Form1的代码,第二段写Form2吧?
  • 不,两个代码部分 - 在 Form1 中。 Form2 中不需要新代码。
  • 是的。那行得通。不知何故,关闭Form2需要两次尝试,但我想我会管理的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多