How do I set a toolstriptextbox accept button to call a function which a toolstripbutton calls?

1.9k Views Asked by At

I have a TextBox in my . When a user starts typing in it I will like to set the AcceptButton property to call another function. However it is calling another function which is called by a Button in my ToolStrip. To elaborate, here is my code below:

private void locNameTxtBx_TextChanged(object sender, EventArgs e)
{
    this.AcceptButton = searchBtn;
}

private void searchBtn_Click_1(object sender, EventArgs e)
{
    if (locNameTxtBx.Text != "")
    {
        List<SearchLocation> locationsArray = new List<SearchLocation>();
        var location = locNameTxtBx.Text;
        SearchLocation loc = new SearchLocation();
        loc.Where = location;
        locationsArray.Add(loc);
        mapArea.VE_FindLocations(locationsArray, true, true, null);
        mapArea.VE_SetZoomLevel(14);
    }
    else
    {
        MessageBox.Show("Please Enter Location");
    }
}

searchBtn is a Button in the ToolStrip. So, when I try to run this code, I get this error

Cannot implicitly convert type 'System.Windows.Forms.ToolStripButton' to 'System.Windows.Forms.IButtonControl'. An explicit conversion exists (are you missing a cast?)

I have tried casting it as a ToolstripButton like this:

private void locNameTxtBx_TextChanged(object sender, EventArgs e)
{
    this.AcceptButton = (ToolStripButton)searchBtn;
}
1

There are 1 best solutions below

0
On

You could use two delegates and set the delegate to use in the locNameTxtBx_TextChanged method.

    private delegate void ToUseDelegate();

    ToUseDelegate delegateIfNoText = delegate{
       MessageBox.Show("Please Enter Location");
    }

    ToUseDelegate delegateIfText = delegate{
       List<SearchLocation> locationsArray = new List<SearchLocation>();
       var location = locNameTxtBx.Text;
       SearchLocation loc = new SearchLocation();
       loc.Where = location;
       locationsArray.Add(loc);
       mapArea.VE_FindLocations(locationsArray, true, true, null);
       mapArea.VE_SetZoomLevel(14);
    }

    ToUseDelegate delToUse = delegateIfNoText;

    private void locNameTxtBx_TextChanged(object sender, EventArgs e)
    {
       this.AcceptButton = searchBtn;
       if (locNameTxtBx.Text != ""){
          delegateToUse = delegateIfNoText;
       } else {
          delegateToUse = delegateIfText;
       }
    }

    private void searchBtn_Click_1(object sender, EventArgs e)
    {
       delegateToUse();
    }