Mohemmad K
Mohemmad K

Reputation: 839

Button_Click() Event fires twice in windows desktop application

I am creating a form in which search option is provided like this

I am working in a MDI form application.

My code is :

 private void btnSearch_Click(object sender, EventArgs e)
 {

    string query = null;
    if (txtBillNo.Enabled && txtBillNo.Text.Trim().Length != 0)
    {
        query = "Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy')as Dt from BillMaster where BillNo=" + Convert.ToInt32(txtBillNo.Text.Trim());
        FillGrid(query);
    }
    else if (txtName.Enabled && txtName.Text.Trim().Length != 0)
    {
            query = "Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy')as Dt from BillMaster where UCASE(PartyName) like '" + txtName.Text.Trim().ToUpper() + "'";
            FillGrid(query);
    }

    else
    {
        MessageBox.Show("Enter Value First");

        if (rdbName.Enabled)
        {
            txtName.Focus();

        }
        else if (rdbBillNo.Enabled)
        {
           txtBillNo.Focus();

        }

    }                 

}

The conditions are for checking whether the text boxes are left or not. If it is left blank then I am giving the message that user must enter the value. But when I am running the program it prompts twice, then I debugged the program and found that the Click event is called twice.

What should I do to tackle this problem.
Please help.

Upvotes: 1

Views: 4475

Answers (4)

cadwiki.net
cadwiki.net

Reputation: 88

I think the method signature might need to be changed to use RoutedEventArgs e

Then, at the end of the method body, you can set e.Handled to True

     private void btnSearch_Click(object sender, RoutedEventArgs e)
 {
    // do some stuff  
    e.Handled = True

}

Upvotes: 0

Dammer15
Dammer15

Reputation: 190

If it's a WPF project make sure you don't have the click Handler registered in XAML and the project's C# code. I had the same issue and it was due to this reason.

Upvotes: 0

Mustafa Ekici
Mustafa Ekici

Reputation: 7470

In WPF you have to set e.Handled to True after FillGrid(query)
In win forms, delete and dont register btnSearch.Click in Load()

Upvotes: 3

Davut Gürbüz
Davut Gürbüz

Reputation: 5716

In Visual Studio Open CallStack and find out which function call Click event while debugging.

Debug->Windows->Call Stack

Upvotes: 0

Related Questions