刷新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;
}
}
}
答案 0 :(得分: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
}