[讨论]Windows程序中如何调用关闭事件?
讨论一下,在Windows程序中如何在点击窗体上的X按钮在关闭窗体前查看是否用户对窗体上的DataGrid中的数据进行了修改,如果已修改则提示保存,否则直接关闭?注意:不是点击自己做的“关闭”按钮,而是点击窗体上的X按钮。我写了个代码,但好像没有实现功能:
private DataTable dt=new DataTable();
private void Form1_Closing(object sender,........)
{
DataRow[] rr=dt.Select("","",DataViewRowState.ModifiedCurrent);
if(rr==null || rr.Length<=0)
{
return;
}
if(MessageBox.Show("您有"+rr.Length.ToString()+"条数据已修改,是否保存?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
{
SqlConnection con=new SqlConnection(.........);
SqlCommand cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandText="update Test set [ID]=@newid,[Name]=@newname,Sex=@newsex where [ID]=@oldid and [Name]=@oldname and Sex=@oldsex";
cmd.Parameters.Add("@newid",SqlDbType.VarChar,10,"ID");
cmd.Parameters.Add("@newname",SqlDbType.VarChar,10,"Name");
cmd.Parameters.Add("@newsex",SqlDbType.Char,2,"Sex");
SqlParameter para=cmd.Parameters.Add("@oldid",SqlDbType.VarChar,10,"ID");
para.SourceVersion=DataRowVersion.Original;
para=cmd.Parameters.Add("@oldname",SqlDbType.VarChar,10,"Name");
para.SourceVersion=DataRowVersion.Original;
para=cmd.Parameters.Add("@oldsex",SqlDbType.Char,2,"Sex");
para.SourceVersion=DataRowVersion.Original;
SqlDataAdapter da=new SqlDataAdapter();
da.UpdateCommand=cmd;
try
{
da.Update(rr);
}
catch(SqlException er)
{
MessageBox.Show(er.Message);
}
}
}