一个链接数据库的按钮btnConnection,在它的Click事件里写SqlDataReader dr = null;
            List<string> collection = new List<string>();
            lblConnectState.Text = "Connectioning..."; //这一行语句显示不出来呀!            try
            {
                SqlConnection connection = new SqlConnection();
                connection.ConnectionString = "Data Source=" + dataSource + @";Initial Catalog=master;Integrated Security=True";
                connection.Open();
                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = @"SELECT Name FROM Master..SysDatabases ORDER BY Name";                dr = command.ExecuteReader();
                while (dr.Read())
                {
                    string DBName = dr.GetString(0);
                    collection.Add(DBName);
                }
            }
            catch (Exception ex)
            {
                lblConnectState.Text = "Connection error!";
                return;
                //throw ex;
            }            lblConnectState.Text = "Connection succeed!";
            if (dr!=null && !dr.IsClosed)
            {
                dr.Close();
            } 
问题是:按钮旁边的label显示链接状态,可是上面那句lblConnectState.Text = "Connectioning..."; 从来没有显示过(不管是连上连不上)。
当数据库链接失败是会停五六秒lblConnectState什么也不显示,五六秒后直接显示Connection error!
是不是线程冲突了?

解决方案 »

  1.   

                lblConnectState.Text = "Connectioning..."; //这一行语句显示不出来呀!后面加上:
                lblConnectState.Refresh();
    如果还不行,换成Application.DoEvents();
      

  2.   

    UI的刷新和你的事件处理都是在主线程上完成的。你的事件处理函数返回之前,主线程是没有机会处理刷新UI的请求的。SqlDataReader dr = null;
                List<string> collection = new List<string>();
                lblConnectState.Text = "Connectioning..."; //这一行语句显示不出来呀!
                
                //加上这句,让主线程去更新UI
                Application.DoEvents();
                
                //或者另外开一个线程来进行数据库操作
      

  3.   

    lblConnectState.Text += "Connection error!";
    lblConnectState.Text += "Connection succeed!";