0

我在刷新 DataGridView 时遇到问题。

Form2从打开Form1,在Form2我添加新记录并关闭Form2,当我回到 DataGridView 所在的 Form1 时,没有任何变化。:(

如果我关闭程序并再次运行它,就会出现新记录。

关闭Form2时如何刷新DataGridView,所以当我回到Form1时有更新的记录?

这是我的示例代码:

Form1 = window with dataviewgrid + 1 button (ADD NEW)

private void button1_Click(object sender, EventArgs e)
    {
        Form2 okno2;
        okno2 = new Form2();
        okno2.Show();
    }

表格2:

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {

        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\ja\documents\visual studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();

        public Form2()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txt_imie.Text !="" & txt_nazwisko.Text !="" & txt_adres.Text !="")
            {
                con.Open();
                cmd.CommandText = "insert into tabelka1 (imie,nazwisko,adres) values ('"+txt_imie.Text+"','"+txt_nazwisko.Text+"','"+txt_adres.Text+"' )"; 
                cmd.ExecuteNonQuery();  

                cmd.Clone();
                MessageBox.Show("Record added");
                cmd.CommandText = "refresh";
                cmd.EndExecuteNonQuery();
                cmd.Connection.Close();

                this.Close();
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            cmd.Connection = con;
        }
    }
}
4

1 回答 1

1

实现 Form2 的 formClosed 事件,然后您可以刷新您的 datagridview。

private void button1_Click(object sender, EventArgs e)
{
    Form2 okno2;
    okno2 = new Form2();
    okno2.Show();
   form2.FormClosed += Form2OnFormClosed;

}

  private void Form2OnFormClosed(object sender, FormClosedEventArgs args)
    {
      // Code for refreshing
    }
于 2013-07-28T09:48:27.907 回答