簡體   English   中英

如何在C#中使用datagridview從數據庫自動刷新數據

[英]how to automatically refresh data from database with datagridview in c#

我有一個具有兩個表單的程序,管理員可以訪問表單A,而隨機用戶則可以使用表單B。

表格A用於搜索注冊用戶列表。 表格B用於注冊。

表單A具有從數據庫中獲取數據的datagridview,我希望datagridview在有人從表單B注冊后自動刷新其中的數據...

我想從數據庫中獲取數據並將其自動放入datagridview中,而無需關閉表單並再次打開它...

對不起,我對此還不是很新。.請給我一些建議和例子...謝謝...

沒有任何代碼很難回答您的問題。 但是通常可以通過執行簡單形式的事件處理來解決此類問題。

在您的情況下, 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;
}

最后要解決的事實是,可以在打開FormA之后打開FormB。 這可能是由於您需要使用以下菜單項代碼進行調整而發生的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM