When the database is asynchronously read, some problems may occur during data binding, that is, the form interface cannot be closed, and the process can only be ended after the task is completed. For example, the following code
First, set the thread to update the UI
A2.checkforillegalcrossthreadcils = false; // a2 indicates the form name.
The following code retrieves data from the database and binds it
Private void button#click (object sender, EventArgs e)
{
SqlConnection con;
SqlCommand com;
Try
{
Con = new SqlConnection ("UID = sa; Password = 123; Initial Catalog = AD; Data Source = 192.168.1.1; Asynchronous Processing = true ");
Con. Open ();
Com = new SqlCommand ("select top 100 * from tb_user", con );
Com. BeginExecuteReader (new AsyncCallback (delDataBin), com );
}
Catch (Exception ex)
{
MessageBox. Show ("program error, Message:" + ex. Message );
}
}
Private void delDataBin (IAsyncResult ar)
{
If (ar. IsCompleted)
{
SqlCommand com = (SqlCommand) ar. AsyncState;
SqlDataReader dr = com. EndExecuteReader (ar );
DataTable dt = new DataTable ();
Dt. Load (dr );
Dr. Close ();
This. Maid = dt; // bind data
}
}
The binding is completed here. Run and check the effect. In fact, the form is suspended.
The following is implemented through Invoke:
First declare the delegate public delegate void updateDG (DataTable dt );
Then bind the DataGridView through dataBin.
Public void dataBin (DataTable dt)
{
DataGridView1.DataSource = dt;
Return;
}
The following method is called in the thread.
// Bind data
If (this. InvokeRequired)
{
UpdateDG ur = new updateDG (dataBin );
This. Invoke (ur, dt );
}
The complete code is as follows:
Private void button#click (object sender, EventArgs e)
{
SqlConnection con;
SqlCommand com;
Try
{
Con = new SqlConnection ("UID = sa; Password = 123; Initial Catalog = AD; Data Source = 192.168.1.1; Asynchronous Processing = true ");
Con. Open ();
Com = new SqlCommand ("select top 100 * from tb_user", con );
Com. BeginExecuteReader (new AsyncCallback (delDataBin), com );
}
Catch (Exception ex)
{
MessageBox. Show ("program error, Message:" + ex. Message );
}
}
Private void delDataBin (IAsyncResult ar)
{
If (ar. IsCompleted)
{
SqlCommand com = (SqlCommand) ar. AsyncState;
SqlDataReader dr = com. EndExecuteReader (ar );
DataTable dt = new DataTable ();
Dt. Load (dr );
Dr. Close ();
// This. Maid = dt; // bind data
If (this. InvokeRequired)
{
UpdateDG ur = new updateDG (dataBin );
This. Invoke (ur, dt );
}