在连接到数据库时显示进度条

时间:2011-03-08 17:49:32

标签: c# .net mysql winforms

我创建了一个使用远程在线MYSQL数据库的Windows应用程序。对于连接,我创建了一个DataConnector()类。每当我想连接时,我都会创建一个DataConnector()类的对象。

实际上我想在连接到数据库期间显示进度条,我的意思是进度条应该在应用程序的顶部,连接成功后进度条应该自动关闭。

需要一些想法如何做到这一点...我尝试过“backgroundworker”但面对prob,因为类中的函数返回“MySqlConnection”类型。

这是我的DataConnector()类..

 namespace omg
{
    class DataConnector
    {
        bool connected = false;
        MySqlConnection connection = null;
        MySqlCommand command;
        string connectionstring = "server=127.0.0.1;database=online_trading_system;UserId=root;Password=phanny";
        public MySqlConnection connect()
        {
            try
            {
                connection = new MySqlConnection(connectionstring);
                connection.Open();
                connected = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return connection;
            }

            MessageBox.Show("connected with the databse");
            // connection.Close();
            //connected = false;
            return connection;
        }
        public void close()
        {
            connection.Close();
            connected = false;
            MessageBox.Show("connection Closed");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的BackgroundWorker方法是正确的。这是一个简短的样本:

private void OpenConnectionButton_Click() {
    var bw = new BackgroundWorker();

    bw.DoWork += (sender, e) => {
        // this will happen in a separate thread
        var connector = new DataConnector();
        connector.connect(); // this might take a while
        e.Result = connector;
    }

    bw.RunWorkerCompleted += (sender, e) => {
        // We are back in the UI thread here.

        // close the progress bar
        ...

        if (e.Error != null)  // if an exception occurred during DoWork,
            MessageBox.Show(e.Error.ToString());  // do your error handling here
        else {
            var connector = (DataConnector)e.Result;
            // do something with your connector
        }
    };

    // show the progress bar
    ...

    bw.RunWorkerAsync(); // start the background worker
}