在写程序时有时会遇到新建一个窗口,填写某些信息后再刷新原窗口。比如在新窗口添加新管理员,点击确定提交后再刷新原始窗口的管理员列表。听起来貌似是很简单,只要再调用一下绑定管理员列表的函数就可以了,但在新窗口调用那个函数是不行的,但是用传递委托的方法可以,代码如下:
C# Winform刷新窗口步骤1
原始窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PAT.DataAccess;
using System.Collections;
namespace PAT.WinForm
{
public partial class RoleManage : Form
{
public delegate void UpdateComoboxAsyscHandler();//作为异步更新角色列表时用的委托,//***使用空参数列表,且要定义为//public
//更新列表的函数,即上面定义的委托要绑定的函数
private void UpdateComobox()
{
WinFormControlBuilder.Instance.BindRoles(comboBoxRoles);
}
private void buttonAddRole_Click(object sender, EventArgs e)
{
//AddRole是添加新角色的窗口,这里把刚写好的委托传进来
AddRole addRole = new AddRole(new UpdateComoboxAsyscHandler(UpdateComobox));
addRole.Show();
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
C# Winform刷新窗口步骤2
新窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PAT.DataAccess;
using System.Threading;
namespace PAT.WinForm
{
public partial class AddRole : Form {
public AddRole()
{
InitializeComponent();
}
private RoleManage.UpdateComoboxAsyscHandler UpdateComoboxAsyscHandler;
//写一个新的构造函数,参数是之前写好的委托
public AddRole(RoleManage.UpdateComoboxAsyscHandler _updateComoboxAsyscHandler)
{
InitializeComponent();
this.UpdateComoboxAsyscHandler = _updateComoboxAsyscHandler;//委托赋值
}
private void buttonSubmit_Click(object sender, EventArgs e)
{
//
//更新数据库操作
//
Accunt_Role account_Role = new Accunt_Role();
account_Role.RoleName = textBoxRoleName.Text;
patDataContext.Accunt_Roles.InsertOnSubmit(account_Role);
patDataContext.SubmitChanges();
UpdateComoboxAsyscHandler();//调用委托,更新原列表
MessageBox.Show("添加角色成功!");
this.Dispose();//关闭窗口
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
效果示例如下:
点击确定后,在始窗口列表中显示:
这样就可以实现在新窗口添加新角色后,新窗口关闭,同时刷新原始窗口的角色列表。
至此,C# Winform刷新窗口的方法就讨论完了。
【编辑推荐】