我有一个程序有两种形式,表单A可由管理员访问,表单B可供随机用户使用。
表单A用于搜索注册用户列表。 表格B用于注册。
表单A具有datagridview,其中包含来自数据库的数据,我希望datagridview在从表单B注册的人之后自动刷新其中的数据...
我想从数据库中获取数据并自动将其放入datagridview而不关闭表单并再次打开它...
抱歉,我还是新来的..请你给我一些建议和例子...... 谢谢......答案 0 :(得分:0)
没有任何代码很难回答你的问题。但通常可以通过简单的事件处理形式解决这类问题。
在您的情况下, FormB 会发布新用户注册的信息。当新用户注册自己时,FormB会检查是否有人注册了自己以通知该事件。 FormA 注册自己以接收事实通知。
在代码中,你在FormB中有这个
public class FormB : Form
{
public delegate void OnNewUserRegistered(string username)
public OnNewUserRegistered NewUserRegistered;
....
protected void cmdRegister_Click(object sender, EventArgs e)
{
// Code to register the user
string username = txtUserName.Text;
..... etc .....
// If someone has registered a subscription then call that subscription handler
if(NewUserRegistered != null)
NewUserRegistered(username);
}
}
根据您的解释,现在最大的问题是FormA在FormB中订阅事件的模式。假设,当FormA加载时,FormB已经打开。您需要搜索FormB的实例
FormA.cs代码
Public FormB RegistrationForm {get; set;}
private void Form_Load(object sender, EventArgs e)
{
// If FormB is open then get its instance
this.RegistrationForm = Application.OpenForms.Cast<Form>().OfType<FormB>().FirstOrDefault ();
if(this.RegistrationForm != null)
{
// Subscribe to the registration event in FormB
RegistrationForm.NewUserRegistered += ANewUserHasBeenRegistered;
// Subscribe to the closed event of FormB
RegistrationForm.Closed += FormBHasBeenClosed;
}
// Now load the current user list in your grid view.
LoadUserList(); // this contains the code that initializes the gridView
}
// this is the subscription method that will be called by the FormB instance
// every time a new user registers with that form
private void ANewUserHasBeenRegistered(string userName)
{
// Here you have two options.
// Reload the grid I.E. call LoadUserList();
// Try to manually add the new user in the current gridview.
.....
}
// this will be called by the framework when FormB instance closes.
// It is important to avoid any possibility to reference a destroyed form
// using the RegistrationForm variable.
private void FormBHasBeenClosed(object sender, FormClosedEventArgs e)
{
this.RegistrationForm = null;
}
要解决的最后一点是FormB可以在FormA打开后打开。这可能来自您需要调整的某种menuItem代码:
FormB f = new FormB();
// Search if there is an instance of FormA around
// If found then pass the instance of the FormB to the RegistrationForm public property of FormA
FormA currentFormA = Application.OpenForms.Cast<Form>().OfType<FormA>().FirstOrDefault ();
if(currentFormA != null)
currentFormA.RegistrationForm = f;
// Allow users to register.....
f.ShowDialog();