1、实现方法
实现通过子窗体刷新父窗体时,主要通过在自定义事件中执行数据绑定来对主窗体进行刷新,即当子窗体产生更新操作时,通过子窗体的一个方法触发主窗体中对应的事件,这个过程主要用到了eventhandler事件。
eventhandler事件主要是通过eventhandler委托来实现的,该委托表示处理不包含事件数据的事件的方法。语法格式如下:
public delegate void eventhandler(object sender,eventargs e) 参数说明 sender:事件源。 e:不包含任何事件数据的eventargs事件数据。
例如,通过使用eventhandler事件为子窗体添加一个事件处理程序,以便能够刷新父窗体中的数据。
在子窗体里:
/// <summary> /// 某一个事件,比如,添加 /// </summary> private void button1_click(object? sender, eventargs e) { globalflag = true; //设定标识的值为true if (!(combobox1.items.equals(idcontent))) //当combobox控件中不存在将添加的信息时 { combobox1.items.add(idcontent!); //在combobox控件中添加一条记录 } updatedata(); } // 其它 /// <summary> /// 更新datagridview控件中的内容 /// </summary> protected void updatedata() { updatedatagridview?.invoke(this, eventargs.empty); }
在主窗体里:
// 添加子窗体的事件 public void createfrmchild() { frm_child babywindow = new() { mdiparent = this, }; datagridview1.controls.add(babywindow); babywindow.updatedatagridview += new eventhandler(babywindow_updatedatagridview!); babywindow.show(); } // 其它 /// <summary> /// 实现事件委托 /// </summary> void babywindow_updatedatagridview(object sender, eventargs e) { // 其它 }
2.sqlcommand类
本实例中使用了sql,主窗体的数据读取自sql,在子窗体里更新,然后回写sql,其结果再次更新到主窗体。
在c#中执行sql语句时,可以使用sqlcommand类,该类主要用于向sql server数据库发送sql语句。
本实例的数据库连接字符串:
//数据库连接字符串 readonly string? connstring = "data source=desktop-3lv13fs;database=db_tomeone;integrated security=sspi;trustservercertificate=true;";
还有,在.net 8.0中,要使用命名空间:using microsoft.data.sqlclient;因为 using system.data.sqlclient; 已经废弃。
3.实例的主窗体frm_main:
(1)frm_main.designer.cs
namespace _197 { partial class frm_main { /// <summary> /// required designer variable. /// </summary> private system.componentmodel.icontainer components = null; /// <summary> /// clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void dispose(bool disposing) { if (disposing && (components != null)) { components.dispose(); } base.dispose(disposing); } #region windows form designer generated code /// <summary> /// required method for designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void initializecomponent() { menustrip1 = new menustrip(); toolstripmenuitem1 = new toolstripmenuitem(); toolstripmenuitem2 = new toolstripmenuitem(); toolstripmenuitem3 = new toolstripmenuitem(); datagridview1 = new datagridview(); menustrip1.suspendlayout(); ((system.componentmodel.isupportinitialize)datagridview1).begininit(); suspendlayout(); // // menustrip1 // menustrip1.backcolor = systemcolors.controldark; menustrip1.items.addrange(new toolstripitem[] { toolstripmenuitem1 }); menustrip1.location = new point(0, 0); menustrip1.name = "menustrip1"; menustrip1.size = new size(335, 25); menustrip1.tabindex = 0; menustrip1.text = "menustrip1"; // // toolstripmenuitem1 // toolstripmenuitem1.dropdownitems.addrange(new toolstripitem[] { toolstripmenuitem2, toolstripmenuitem3 }); toolstripmenuitem1.name = "toolstripmenuitem1"; toolstripmenuitem1.size = new size(44, 21); toolstripmenuitem1.text = "操作"; // // toolstripmenuitem2 // toolstripmenuitem2.name = "toolstripmenuitem2"; toolstripmenuitem2.size = new size(136, 22); toolstripmenuitem2.text = "添加或删除"; toolstripmenuitem2.click += toolstripmenuitem2_click; // // toolstripmenuitem3 // toolstripmenuitem3.name = "toolstripmenuitem3"; toolstripmenuitem3.size = new size(136, 22); toolstripmenuitem3.text = "退出"; toolstripmenuitem3.click += toolstripmenuitem3_click; // // datagridview1 // datagridview1.allowusertoaddrows = false; datagridview1.columnheadersheightsizemode = datagridviewcolumnheadersheightsizemode.autosize; datagridview1.dock = dockstyle.fill; datagridview1.location = new point(0, 25); datagridview1.name = "datagridview1"; datagridview1.size = new size(335, 178); datagridview1.tabindex = 1; // // frm_main // autoscaledimensions = new sizef(7f, 17f); autoscalemode = autoscalemode.font; clientsize = new size(335, 203); controls.add(datagridview1); controls.add(menustrip1); ismdicontainer = true; mainmenustrip = menustrip1; name = "frm_main"; text = "主窗体"; load += frm_main_load; menustrip1.resumelayout(false); menustrip1.performlayout(); ((system.componentmodel.isupportinitialize)datagridview1).endinit(); resumelayout(false); performlayout(); } #endregion private menustrip menustrip1; private toolstripmenuitem toolstripmenuitem1; private toolstripmenuitem toolstripmenuitem2; private toolstripmenuitem toolstripmenuitem3; private datagridview datagridview1; } }
(2)frm_main.cs
// 通过子窗体刷新父窗体 // 设置主窗体的ismdicontainer=true; using system.data; using microsoft.data.sqlclient; namespace _197 { public partial class frm_main : form { public frm_main() { initializecomponent(); } #region 声明的变量 private static bool flag = false; //标识是否创建新的子窗体 readonly frm_child babywindow = new();//实例化一个子窗体 readonly dataset pubsset = new(); //定义一个数据集对象 private static string[]? idarray; //声明一个一维字符串数组 public datatable? idtable; //声明一个数据表对象 sqldataadapter? idadapter; //声明一个数据读取器对象 sqldataadapter? pubsadapter; //声明一个数据读取器对象 sqlconnection? connpubs; //声明一个数据库连接对象 sqlcommand? personalinformation; //声明一个执行sql语句的对象 public static string[]? idarray { get => idarray; set => idarray = value; } public static bool flag { get => flag; set => flag = value; } readonly string? connstring //数据库连接字符串 = "data source=desktop-3lv13fs;database=db_tomeone;integrated security=sspi;trustservercertificate=true;"; #endregion private void frm_main_load(object? sender, eventargs e) { string adapterstring = "select userid as 编号,username as 姓名 ,phone as 电话,address as 住址 from tb_user";//用于查询的字符串 string idstring = "select userid from tb_user";//读取数据库中用户的id编号字符串 connpubs = new sqlconnection(connstring);//建立数据库连接 pubsadapter = new sqldataadapter(adapterstring, connpubs);//创建pubsadapter数据读取器 idadapter = new sqldataadapter(idstring, connpubs); //用于读取用户编号的读取器 pubsadapter.fill(pubsset, "tb_user"); //填充pubsset数据集 idadapter.fill(pubsset, "id"); //填充pubsset数据集 datatable pubstable = pubsset.tables["tb_user"]!;//将数据写入pubstable表 idtable = pubsset.tables["id"]!; //将数据写入id表 idarray = new string[idtable.rows.count]; //为数组定义最大长度 datagridview1.datasource = pubstable.defaultview;//设置datagridview1的数据源 for (int i = 0; i < idtable.rows.count; i++) //循环遍历数据表中的每一行数据 { for (int j = 0; j < idtable.columns.count; j++)//循环遍历数据表中的每一列数据 { idarray[i] = idtable.rows[i][j].tostring()!;//将数据表中的数据添加至一个一维数组 } } } #region 创建子窗体的createfrmchild方法 /// <summary> /// 设置子窗体的父窗体为当前窗体; /// 实例化一个子窗体; /// 在datagridview控件中添加子窗体; /// 显示子窗体; /// </summary> public void createfrmchild() { frm_child babywindow = new() { mdiparent = this, }; datagridview1.controls.add(babywindow); babywindow.updatedatagridview += new eventhandler(babywindow_updatedatagridview!); babywindow.show(); } /// <summary> /// 事件委托 /// </summary> void babywindow_updatedatagridview(object sender, eventargs e) { if (frm_child.globalflag == false) //当单击删除按钮时 { if (connpubs!.state == connectionstate.closed) //当数据库处于断开状态时 { connpubs.open(); //打开数据库的连接 } string afreshstring = "delete tb_user where userid=" + frm_child.deleteid!.trim();//定义一个删除数据的字符串 personalinformation = new sqlcommand(afreshstring, connpubs); //执行删除数据库字段 personalinformation.executenonquery(); //执行sql语句并返回受影响的行数 connpubs.close(); //关闭数据库 displaydata(); //显示数据库更新后的内容 messagebox.show("数据删除成功!", "提示信息", messageboxbuttons.ok, messageboxicon.asterisk); } else { if (connpubs!.state == connectionstate.closed) //当数据库处于关闭状态时 { connpubs.open(); //打开数据库 } string insertstring = "insert into tb_user values('" + frm_child.idcontent + "','" + frm_child.namecontent + "','" + frm_child.phonecontent + "','" + frm_child.addresscontent + "')";//定义一个插入数据的字符串变量 personalinformation = new sqlcommand(insertstring, connpubs);//执行插入数据库字段 personalinformation.executenonquery(); //执行sql语句并返回受影响的行数 connpubs.close(); //关闭数据库 displaydata(); //显示更新后的数据 messagebox.show("数据添加成功!", "提示信息", messageboxbuttons.ok, messageboxicon.asterisk); } } #endregion #region 用于读取数据库的displaydata方法 public void displaydata() { pubsset.clear(); connpubs = new sqlconnection(connstring); string displaystring = "select userid as 编号,username as 姓名 ,phone as 电话,address as 住址 from tb_user";//定义读取数据库的字段 sqldataadapter personaladapter = new(displaystring, connpubs); //定义一个读取数据库数据的读取器 personaladapter.fill(pubsset, "tb_user"); //向表displaytable中填充数据 datagridview1.datasource = pubsset.tables["tb_user"]!.defaultview; //设定datagridview控件的数据源 } #endregion /// <summary> /// 添加或删除记录 /// 创建子窗体的createfrmchild方法 /// </summary> private void toolstripmenuitem2_click(object sender, eventargs e) { if (flag == false) //判断标识的值决定是否创建窗体 { createfrmchild();//创建子窗体 } for (int i = 0; i < datagridview1.controls.count; i++) //循环遍历datagridview控件上的控件集 { if (datagridview1.controls[i].name.equals(babywindow.name)) //当存在子窗体时 { flag = true; //改变标识flag的值 break; //退出循环体 } } } /// <summary> /// 退出 /// </summary> private void toolstripmenuitem3_click(object sender, eventargs e) { application.exit(); } } }
4.实例的子窗体frm_child:
(1) frm_child.designer.cs
namespace _197 { partial class frm_child { /// <summary> /// required designer variable. /// </summary> private system.componentmodel.icontainer components = null; /// <summary> /// clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void dispose(bool disposing) { if (disposing && (components != null)) { components.dispose(); } base.dispose(disposing); } #region windows form designer generated code /// <summary> /// required method for designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void initializecomponent() { groupbox1 = new groupbox(); button2 = new button(); button1 = new button(); record_address = new textbox(); record_phone = new textbox(); record_name = new textbox(); record_id = new textbox(); label4 = new label(); label3 = new label(); label2 = new label(); label1 = new label(); groupbox2 = new groupbox(); button3 = new button(); combobox1 = new combobox(); label5 = new label(); groupbox1.suspendlayout(); groupbox2.suspendlayout(); suspendlayout(); // // groupbox1 // groupbox1.controls.add(button2); groupbox1.controls.add(button1); groupbox1.controls.add(record_address); groupbox1.controls.add(record_phone); groupbox1.controls.add(record_name); groupbox1.controls.add(record_id); groupbox1.controls.add(label4); groupbox1.controls.add(label3); groupbox1.controls.add(label2); groupbox1.controls.add(label1); groupbox1.location = new point(12, 12); groupbox1.name = "groupbox1"; groupbox1.size = new size(270, 157); groupbox1.tabindex = 0; groupbox1.tabstop = false; groupbox1.text = "添加信息"; // // button2 // button2.location = new point(187, 56); button2.name = "button2"; button2.size = new size(75, 23); button2.tabindex = 9; button2.text = "清空"; button2.usevisualstylebackcolor = true; button2.click += button2_click; // // button1 // button1.location = new point(187, 25); button1.name = "button1"; button1.size = new size(77, 23); button1.tabindex = 8; button1.text = "提交"; button1.usevisualstylebackcolor = true; button1.click += button1_click; // // record_address // record_address.location = new point(72, 118); record_address.name = "record_address"; record_address.size = new size(100, 23); record_address.tabindex = 7; record_address.textchanged += record_address_textchanged; // // record_phone // record_phone.location = new point(72, 87); record_phone.name = "record_phone"; record_phone.size = new size(100, 23); record_phone.tabindex = 6; record_phone.textchanged += record_phone_textchanged; // // record_name // record_name.location = new point(72, 56); record_name.name = "record_name"; record_name.size = new size(100, 23); record_name.tabindex = 5; record_name.textchanged += record_name_textchanged; // // record_id // record_id.location = new point(72, 25); record_id.name = "record_id"; record_id.size = new size(100, 23); record_id.tabindex = 4; record_id.textchanged += record_id_textchanged; // // label4 // label4.autosize = true; label4.location = new point(11, 118); label4.name = "label4"; label4.size = new size(44, 17); label4.tabindex = 3; label4.text = "地址:"; // // label3 // label3.autosize = true; label3.location = new point(11, 87); label3.name = "label3"; label3.size = new size(44, 17); label3.tabindex = 2; label3.text = "电话:"; // // label2 // label2.autosize = true; label2.location = new point(11, 56); label2.name = "label2"; label2.size = new size(44, 17); label2.tabindex = 1; label2.text = "姓名:"; // // label1 // label1.autosize = true; label1.location = new point(11, 25); label1.name = "label1"; label1.size = new size(44, 17); label1.tabindex = 0; label1.text = "编号:"; // // groupbox2 // groupbox2.controls.add(button3); groupbox2.controls.add(combobox1); groupbox2.controls.add(label5); groupbox2.location = new point(12, 175); groupbox2.name = "groupbox2"; groupbox2.size = new size(270, 54); groupbox2.tabindex = 1; groupbox2.tabstop = false; groupbox2.text = "删除信息"; // // button3 // button3.location = new point(187, 24); button3.name = "button3"; button3.size = new size(75, 23); button3.tabindex = 2; button3.text = "删除"; button3.usevisualstylebackcolor = true; button3.click += button3_click; // // combobox1 // combobox1.formattingenabled = true; combobox1.location = new point(72, 24); combobox1.name = "combobox1"; combobox1.size = new size(100, 25); combobox1.tabindex = 1; // // label5 // label5.autosize = true; label5.location = new point(11, 30); label5.name = "label5"; label5.size = new size(44, 17); label5.tabindex = 0; label5.text = "编号:"; // // frm_child // autoscaledimensions = new sizef(7f, 17f); autoscalemode = autoscalemode.font; clientsize = new size(294, 241); controls.add(groupbox2); controls.add(groupbox1); maximizebox = false; //最大化按钮没有意义 name = "frm_child"; startposition = formstartposition.centerscreen; text = "子窗体"; formclosing += frm_child_formclosing; load += frm_child_load; groupbox1.resumelayout(false); groupbox1.performlayout(); groupbox2.resumelayout(false); groupbox2.performlayout(); resumelayout(false); } #endregion private groupbox groupbox1; private textbox record_address; private textbox record_phone; private textbox record_name; private textbox record_id; private label label4; private label label3; private label label2; private label label1; private groupbox groupbox2; private button button2; private button button1; private button button3; private combobox combobox1; private label label5; } }
(2)frm_child.cs
// 本实例仅可创建一个窗口: // 最大化后没有实际意义,因此关闭maximizebox属性值为false namespace _197 { public partial class frm_child : form { #region 变量的声明 public event eventhandler? updatedatagridview = null;//定义一个处理更新datagridview控件内容的方法 private static string? deleteid; //定义一个表示删除数据编号的字符串 private static string? idcontent; //该变量用来存储数据编号 private static string? namecontent; //该变量用来存储姓名 private static string? phonecontent; //该变量用来存储电话 private static string? addresscontent; //该变量用来存储住址 private static bool globalflag; //该变量用来标识是否创建新的子窗体 public static string? deleteid { get => deleteid; set => deleteid = value; } public static string? idcontent { get => idcontent; set => idcontent = value; } public static string? namecontent { get => namecontent; set => namecontent = value; } public static string? phonecontent { get => phonecontent; set => phonecontent = value; } public static string? addresscontent { get => addresscontent; set => addresscontent = value; } public static bool globalflag { get => globalflag; set => globalflag = value; } #endregion public frm_child() { initializecomponent(); } /// <summary> /// 添加 /// </summary> private void button1_click(object? sender, eventargs e) { globalflag = true; //设定标识的值为true if (!(combobox1.items.equals(idcontent))) //当combobox控件中不存在将添加的信息时 { combobox1.items.add(idcontent!); //在combobox控件中添加一条记录 } updatedata(); } /// <summary> /// 清空 /// </summary> private void button2_click(object? sender, eventargs e) { record_id.clear(); //清空编号文本框中的内容 record_name.clear(); //清空姓名文本框中的内容 record_phone.clear(); //清空电话号码文本框中的内容 record_address.clear(); //清空居住地址文本框中的内容 record_id.focus(); //设定当前鼠标的焦点在编号文本框中 } /// <summary> /// 删除 /// </summary> private void button3_click(object? sender, eventargs e) { globalflag = false; //设定全局变量表示为false if (combobox1.items.count > 1) //当combobox中剩不小于2条内容时 { deleteid = combobox1.selecteditem!.tostring(); //将选中项转化为int型 if (combobox1.items.count != 0) //当combobox中剩1条内容时 { combobox1.items.remove(combobox1.selecteditem); combobox1.selectedindex = 0; } } updatedata(); } /// <summary> /// 保存新添加记录的编号 /// </summary> private void record_id_textchanged(object? sender, eventargs e) { idcontent = record_id.text; } /// <summary> /// 保存填入的姓名 /// </summary> private void record_name_textchanged(object? sender, eventargs e) { namecontent = record_name.text; } /// <summary> /// 保存填入的电话号码 /// </summary> private void record_phone_textchanged(object? sender, eventargs e) { phonecontent = record_phone.text; } /// <summary> /// 保存填入的地址信息 /// </summary> private void record_address_textchanged(object? sender, eventargs e) { addresscontent = record_address.text; } /// <summary> /// 循环遍历数组中的每一个元素,向combobox控件中添加内容 /// 默认设定当前选中项的索引为0 /// </summary> private void frm_child_load(object? sender, eventargs e) { for (int i = 0; i < frm_main.idarray!.length; i++) { combobox1.items.add(frm_main.idarray[i].tostring()); combobox1.selectedindex = 0; } } /// <summary> /// 设定该值为false表示可以创建新窗体 /// </summary> private void frm_child_formclosing(object? sender, formclosingeventargs e) { frm_main.flag = false; } /// <summary> /// 更新datagridview控件中的内容 /// </summary> protected void updatedata() { updatedatagridview?.invoke(this, eventargs.empty); } } }
5.生成效果
(1)生成
(2)添加
(3)添加后
(4)清空
以上就是c#通过子窗体刷新父窗体的实现方法的详细内容,更多关于c#子窗体刷新父窗体的资料请关注代码网其它相关文章!
发表评论