我在刷新 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;
}
}
}