Home > Enterprise >  Label Text not changing on C /CLR Windows Forms
Label Text not changing on C /CLR Windows Forms

Time:10-30

I am working on a small C /CLR Windows Forms Project on Visual Studios Community 2019 using .NET Framework 4.0 in which I have a Combo Box and a Label.

The code fragment below works fine:

private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
            label1->Text = "comboBox1->Text";
        }

But if I add a Sleep(1000); after label1->Text = "comboBox1->Text";, I expect the label to change before the sleep period, but it changes after the sleep period is over.

In general, the label1->Text = "comboBox1->Text"; gets executed after whatever is below that line.

For the below code fragment, I want the program to sleep after changing the label1 Text.

private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
            label1->Text = "comboBox1->Text";
            Sleep(1000);
        }

CodePudding user response:

I understand what you mean. To implement this function, you need to use a timer. You need to add a timer to your WinForm, and then set the Interval value to 1000 in the timer property. You need to use Start to start the timer, you could refer to my code.

this->timer1->Interval = 1000;

this->timer1->Tick = gcnew System::EventHandler(this, &MyForm::timer1_Tick);

timer1->Start();

private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { label1->Text = comboBox1->Text; }

  • Related