Samer_Azar
Samer_Azar

Reputation: 433

Prevent entering button event more than one time

I am using simple asp:Button to save a text box content to DB only once.

protected void btnSave_Click(object sender, EventArgs e)
{
  If(txtMessage.text != string.Empty)
  {
    // Insert into DB Method
    txtMessage.Text = string.Empty;
  }
}

The problem is when I double click the button, the text box won't be cleared, and the debugger enters the condition, therefore saves the content twice

Any help?

Upvotes: 0

Views: 57

Answers (1)

Ahmad Al Sayyed
Ahmad Al Sayyed

Reputation: 596

Save the last button click time and compare it when handling the click

something like:

    TimeSpan LastClick = DateTime.Now.TimeOfDay;
    private void button1_Click(object sender, EventArgs e)
    {
        lock (this)
        {
            if (DateTime.Now.TimeOfDay.Subtract(LastClick).TotalMilliseconds < 500)
                return;
        }
        LastClick = DateTime.Now.TimeOfDay;
        if(txtMessage.text != string.Empty)
        {
          // Insert into DB Method
              txtMessage.Text = string.Empty;
        }
    }

Upvotes: 1

Related Questions