c # DataGirdView dynamic refresh

using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;

DataGirdView namespace
{
public partial class the Form1: Form1
{
the Thread myThread;
String DBConnationstring = "Database Connection";
the MySqlCommand cmd;
the MySqlConnection CON;
the MySqlDataAdapter MSDA;
public int Frequency = 0; // update frequency
public static bool isUse = false; // whether to stop updating
public static string statusInfo = string.Empty; // state
private delegate void myDelegate (DataTable dt) ; // define a delegate
public the Form1 ()
{
the InitializeComponent ();
Label2.Text = "update frequency is:" + (trackBar1 .Value / 1000) .ToString () + " s";
}

void the Form1_Load Private (SENDER Object, EventArgs E)
{
myThread the Thread new new = (startFillDv); // instantiate thread
myThread.Start ();

}

void startFillDv Private ()
{
the while (to true)
{
IF (isUse)
{
the StatusInfo = "data is updated in real time ......";
DataTable dt = getData ( "the SELECT * from orderimpoert"); // Write your own data packaging class can return a DataTable
the Grid (dt);
the Thread.Sleep (Frequency);
}
the else
{
the StatusInfo = "update stop!";
}
}

}

private void Grid(DataTable dt)
{
if (this.InvokeRequired)
{
this.Invoke(new myDelegate(Grid), new object[] { dt });
}
else
{
try
{
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = dt;
dt = null;
statusInfo = "更新完成!";
}
catch
{

}
}

}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (this.myThread.IsAlive)
{
this.myThread.Abort();//结束线程
}
}

private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = statusInfo;
frequency = trackBar1.Value;
if (statusInfo.Trim() == "正在实时更新数据......")
{
pictureBox1.Visible = true;
}
else
{
pictureBox1.Visible = false;
}

}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
isUse = true;
}
else
{
isUse = false;
}

}

private void trackBar1_Scroll(object sender, EventArgs e)
{
label2.Text = "更新频率为:" + (trackBar1.Value / 1000).ToString() + "秒";
}
public DataTable getdata(string sql)
{

try
{
con = new MySqlConnection(DBConnationstring);
con.Open();
cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
msda = new MySqlDataAdapter(cmd);
msda.Fill(dt);
con.Close();
con.Dispose();
return dt;
}
catch (Exception ex)
{
con.Close();
con.Dispose();
return null;
}
}
public int ExecSql(string sql)
{
int a = 0;
try
{
con = new MySqlConnection(DBConnationstring);
con.Open();
cmd = new MySqlCommand(sql, con);
a = cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
return a;
}
catch (Exception)
{
con.Close();
con.Dispose();
return -1;
}
}
}
}

 

 

 

-----------------------------------------------------------------------------------------

Source: https: //files-cdn.cnblogs.com/files/Zingu/DataGirdView.rar

Guess you like

Origin www.cnblogs.com/Zingu/p/11447652.html