Code
delegate void WriteLabelText(string str, Color color);
private void showSqlConnResult(string msg, Color color)
{
this.labelSqlConnStatus.Text = msg;
this.labelSqlConnStatus.ForeColor = color;
this.buttonTestSqlConn.Enabled = true;
}
private void threadTestConn()
{
string result = "连接数据库成功。";
Color color = Color.Green;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this.textBoxSqlConnString.Text.Trim());
try
{
conn.Open();
conn.Close();
}
catch (Exception E)
{
result = E.Message;
color = Color.Red;
}
WriteLabelText wt = new WriteLabelText(showSqlConnResult);
this.Invoke(wt, result, color);
}
private void buttonTestSqlConn_Click(object sender, EventArgs e)
{
this.buttonTestSqlConn.Enabled = false;
this.labelSqlConnStatus.ForeColor = Color.Blue;
this.labelSqlConnStatus.Text = "正在测试连接数据库……";
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.threadTestConn));
thread.Start();
}
delegate void WriteLabelText(string str, Color color);
private void showSqlConnResult(string msg, Color color)
{
this.labelSqlConnStatus.Text = msg;
this.labelSqlConnStatus.ForeColor = color;
this.buttonTestSqlConn.Enabled = true;
}
private void threadTestConn()
{
string result = "连接数据库成功。";
Color color = Color.Green;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this.textBoxSqlConnString.Text.Trim());
try
{
conn.Open();
conn.Close();
}
catch (Exception E)
{
result = E.Message;
color = Color.Red;
}
WriteLabelText wt = new WriteLabelText(showSqlConnResult);
this.Invoke(wt, result, color);
}
private void buttonTestSqlConn_Click(object sender, EventArgs e)
{
this.buttonTestSqlConn.Enabled = false;
this.labelSqlConnStatus.ForeColor = Color.Blue;
this.labelSqlConnStatus.Text = "正在测试连接数据库……";
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.threadTestConn));
thread.Start();
}
http://blog.csdn.net/renguangyong/archive/2007/09/26/1802149.aspx