Reputation: 1
I have a problem with refreshing DataGridView.
I open Form2
from Form1
, in Form2
I add new record and close Form2
, when I'm back to Form1 where DataGridView is, there are no changes. :(
If I close program and run it again, new records are there.
How to refresh DataGridView when I close Form2, so when I go back to Form1 there are updated records?
Here is my sample code:
Form1 = window with dataviewgrid + 1 button (ADD NEW)
private void button1_Click(object sender, EventArgs e)
{
Form2 okno2;
okno2 = new Form2();
okno2.Show();
}
Form2:
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;
}
}
}
Upvotes: 0
Views: 84
Reputation: 3313
Implement the formClosed event of Form2 then you can refresh your 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
}
Upvotes: 1