-1

I have created an app in c#, which sends SMS after a defined time gap, for this I am using timer and a label which count number of record(sent messages). now when I click on submit button to start sending sms, it fetches records from DB but when it come to that label portion which shows number of sms it shows an error message System.InvalidOperationExecution Cross-thread operation not valid control 'lblXXX' accessed from a thread other than the thread it was created. My Code is For Button

private void btnSend_Click(object sender, EventArgs e)
        {
            this.btnSend.Enabled = false;
            this.starttimer();
        }

For Timer

private void starttimer()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Start();
            timer.Interval = 3000;
            timer.Elapsed += new ElapsedEventHandler(this.time_elapsed);

        }

for Lable

while (this.dr.Read())
                        {
                            this.lblWeightSMS.Text = Convert.ToString(Convert.ToInt32(this.lblWeightSMS.Text) + 1);
Ravi
  • 1,744
  • 2
  • 20
  • 37
  • http://stackoverflow.com/questions/14744589/control-accessed-on-a-thread-other-than-the-thread-it-was-created-on – Mohammad Arshad Alam Dec 27 '13 at 16:45
  • 2
    Short answer is your timer callback is occurring on a different thread than the UI. You then try to write a value to a control on the UI thread, from the timer thread. You will need to look at `BeginInvoke` to invoke the call on the UI thread. – Grant H. Dec 27 '13 at 16:46

1 Answers1

2

You need to invoke the call on the UI thread. Try this:

public void SetLblWeight(string lblWeight)
{ 
    if (this.lblWeightSMS.InvokeRequired)
    {
        this.lblWeightSMS.Invoke(new Action<string>(SetLblWeight), lblWeight);
        return;
    }      
    this.lblWeightSMS.Text = lblWeight;

}

And your line this.lblWeightSMS.Text = ... would become SetLblWeight(Convert.ToString(Convert.ToInt32(this.lblWeightSMS.Text) + 1);

Grant H.
  • 3,689
  • 2
  • 35
  • 53
  • **Can not implicitly convert type void to string** :( – Ravi Dec 27 '13 at 17:18
  • @Ravi, seems to work fine. The function is void, don't assign it to the text property of the label (the function does that), which is what I suspect you are doing. Do not use `this.lblWeight.Text = SetLblWeight(...)`, it should simply read `SetLblWeight(...)` – Grant H. Dec 27 '13 at 19:44