0

TextBox我的中有一个。当用户开始输入时,我想设置该AcceptButton属性以调用另一个函数。然而,它正在调用另一个由Buttonmy中的 a 调用的函数ToolStrip。详细地说,这是我的代码如下:

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");
    }
}

searchBtnButton中的一个ToolStrip。因此,当我尝试运行此代码时,出现此错误

无法将类型“System.Windows.Forms.ToolStripButton”隐式转换为“System.Windows.Forms.IButtonControl”。存在显式转换(您是否缺少演员表?)

我曾尝试将其转换为 ToolstripButton,如下所示:

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

1 回答 1

0

您可以使用两个委托并将委托设置为在locNameTxtBx_TextChanged方法中使用。

    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();
    }
于 2012-12-07T15:38:57.747 回答