表单1中的datagridview在从表单2插入后自动刷新
本文关键字:表单 刷新 插入 中的 datagridview | 更新日期: 2023-09-27 18:21:17
我有一个小问题,我在form1中有datagridview,我使用SQL命令将来自form2的数据插入其中,但在单击包括insert命令的按钮后,新插入的值不会出现在form1的datagridview中。有什么办法解决这个问题吗?
所以我不得不在form1中制作刷新按钮,这样每次插入东西时都可以刷新它。
提前谢谢。
这是表单2中的插入代码按钮点击:private void btn_zaj_uloz_Click(对象发送方,EventArgs e){
SqlCommand prikaz = new SqlCommand
("INSERT INTO zajezd(akce,name,zeme,hotel,h_adresa,odjdate,pridate,pocdnu,pocnoc,klimax)values(@zakce,@zname,@zzeme,@zhotel,@zh_adresa,@zodjdate,@zpridate,@zpocdnu,@zpocnoc,@zklimax)", spojeni);
prikaz.Parameters.AddWithValue("zakce", zakce.Text);
prikaz.Parameters.AddWithValue("zname", zname.Text);
prikaz.Parameters.AddWithValue("zzeme", zzeme.Text);
prikaz.Parameters.AddWithValue("zhotel", zhotel.Text);
prikaz.Parameters.AddWithValue("zh_adresa", zh_adresa.Text);
prikaz.Parameters.AddWithValue("zodjdate", zodjdate.Text);
prikaz.Parameters.AddWithValue("zpridate", zpridate.Text);
prikaz.Parameters.AddWithValue("zpocdnu", zpocdnu.Text);
prikaz.Parameters.AddWithValue("zpocnoc", zpocnoc.Text);
prikaz.Parameters.AddWithValue("zklimax", zklimax.Text);
spojeni.Open();
prikaz.ExecuteNonQuery();
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter SDA = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM zajezd", spojeni);
SDA.Fill(dt);
spojeni.Close();
this.Close();
}
关于代码的一些想法。除非我遗漏了什么,否则代码片段会插入(没关系),然后读取所有数据,但对结果什么都不做,所以Form1实际上根本没有意识到发生了什么。
您需要做的是通知Form1 Form2已经完成了插入,并将数据传回。网格应该有某种数据源,从那里可以显示行,您需要在那里添加Form2中新创建的数据。我能想到的最好的方法是在Form2上创建一个Form1将订阅的事件,传递重新创建记录所需的所有数据。
首先创建事件处理程序数据:
public class InsertCompleteEventArgs : EventArgs
{
public string zakce {get;set;}
public string zname {get;set;}
/*other fields go here*/
}
在Form2中,声明事件:
public event EventHandler<InsertCompleteEventArgs> InsertComplete;
protected void OnInsertComplete(string zakce, string zname /*other data*/)
{
EventHandler<InsertCompleteEventArgs> handler = this.InsertComplete;
if(handler!=null)
{
handler(this,new InsertCompleteEventArgs(){zakce=zakce,zname=zname});
}
}
在您的代码中,替换额外的"SELECT*FROM zajezd",引发事件:
This.OnInsertComplete(zakce.Text,zname.Text);
因此,每次插入新记录时,Form2都会引发一个事件,因此任何感兴趣的人都可以知道何时更新自己。剩下要做的就是在启动Form2:时从Form1订阅该事件
public Button_Click(object sender, EventArgs e)
{
/* This will be your existing code when you show Form2 */
Form2 form=new Form2();
form.Insertcomplete += this.Form2_InsertComplete; //this is where the notification is requested
form.Show();
}
public Form2_InsertComplete(object sender, InsertCompleteEventArgs e)
{
/* From here you add the new record to the existing DataSource of the DataGridView using the properties of the "e" object you receive */
}