简体   繁体   中英

How to instantly change label text during a method at runtime?

I've searched through stackoverflow but cannot find the answer. I don't know if I could make this question clearly. I'm not an English-speaking person anyway =.=

I'm using c# and visual studio 2010 to develop. I'm making a Form for user to login, I would like this form test sql server connection during load event.

It seems easy, the code is:

    private void testDBconnection()
    {
        label3.Text = "Connecting to Database Server......";

        SqlServerConnection ssc = new SqlServerConnection();
        bool conOK = ssc.isConnectable(ssc.makeConnectionString(
            SqlServerConnParamters.SqlServerIPAddress,
            SqlServerConnParamters.AccountValidationDatabaseName,
            SqlServerConnParamters.SqlServerUserName,
            SqlServerConnParamters.SqlServerPassword,
            5));
        if (conOK)
        {
            label3.Text = "";
        }
        else
        {
            label3.Text = "Database connection failed";
            button1.Enabled = false;
        }
    }

I put this method in Form_Load event.

But in runtime, this process start even before this form shows. And the validation could last for 15 seconds by default(I set it to 5 but it also takes time). If the connection has some problem, it will display like the programe failed to open, but it will shown after it failed to connect to database.

My intention is tell the user by Label3 displaying "Connecting to Database Server......", and tell user if connection failed.

I was trying to find Form Event like "Loaded_Complete", or "Loaded"(I found Form_Closed though), but I couldn't.

I guess it has something to do with thread, programe sleeping, or else. I hope someone could help me on this. Thanks a lot guys!

I would use a BackgroundWorker this way. That will defer the database check operation, and the form load will not be locked by it.

label3.Text = "Connecting...";
button1.Enabled = false;

var bkw = new BackgroundWorker();
bkw.DoWork += (s, ev) =>
    {
        SqlServerConnection ssc = new SqlServerConnection();
        ev.Result = ssc.isConnectable(ssc.makeConnectionString(
                        SqlServerConnParamters.SqlServerIPAddress,
                        SqlServerConnParamters.AccountValidationDatabaseName,
                        SqlServerConnParamters.SqlServerUserName,
                        SqlServerConnParamters.SqlServerPassword, 5));
    };

bkw.RunWorkerCompleted += (s, ev) =>
    {
        if ((bool)ev.Result == true)
        {
            label3.Text = "Connected";
            button1.Enabled = true;
        }
        else
        {
            label3.Text = "Database connection failed";
        }

        bkw.Dispose();
    };

bkw.RunWorkerAsync();

However, this would require some exception handling. If an exception occurs in the DoWork event, then you can check in the RunWorkerCompleted event wether ev.Error is null or not (it contains the exception) and react accordingly.

Use timer . In form load event start the timer (set interval to 2 sec or what ever you want). As timer ticks call your connection method. At the starting of your testDBconnection() method, stop the timer and dispose it because you don't need it any more.

You should not be using the Form_Load event to fire events when a form loads, you should override the OnLoad() method instead, that way you control when the code gets fired (it's possible for multiple subscribers to be listening to Form_Load and you don't know what order they will run in).

The quickest and dirtiest way of getting the screen to refresh is to Add

Application.DoEvents();

After changing the label, this forces the screen to update. In general though this is bad practice and the background thread above would be a better solution long term.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM