如何在 C# 中使用 DataGridView 自动刷新数据库中的数据

本文关键字:刷新 数据库 数据 DataGridView | 更新日期: 2023-09-27 18:32:35

我有一个有两个表单的程序,表单A可由管理员访问,表单B供随机用户使用。

表格A用于搜索注册用户列表。表格B用于注册。

表单 A 具有包含来自数据库的数据的数据网格视图,我希望数据网格视图在有人从表单 B 注册后自动刷新其中的数据......

我想从数据库中获取数据并自动将其放入 datagridview,而无需关闭表单并再次打开它......

对不起,我还是新手。.你能给我一些建议和例子吗...谢谢。。。

如何在 C# 中使用 DataGridView 自动刷新数据库中的数据

没有任何代码很难回答你的问题。但通常这种问题可以通过简单的事件处理形式来解决。

在您的情况下,FormB 会发布新用户已注册的信息。当新用户自行注册时,FormB 会检查是否有人注册了自己以接收事件通知。表格A注册自己以接收事实通知。

在代码中,您可以在 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 加载时,窗体 B 已打开。您需要搜索 FormB 的实例

表单 A.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打开后打开。这可能是从某种菜单项代码中发生的,您需要使用它进行调整:

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();