Reputation: 1
I've created windows application which uses an remote online MYSQL database.For connection i've created a DataConnector() Class. Everytime when i want to connect I create an object of DataConnector() class.
Actually I want to show the progressbar during the connection takes place to database, i mean the progressbar should be on the top of application, after connection successful the progressbar should close automatically.
need some idea how to do it...I've tried with "backgroundworker" but facing prob as the function inside the class returns "MySqlConnection" type.
Here is my DataConnector() Class..
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");
}
}
}
Upvotes: 0
Views: 5367
Reputation: 172220
Your BackgroundWorker approach was correct. Here's a short sample:
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
}
Upvotes: 1