输入C#关闭下拉列表

时间:2013-06-16 13:49:40

标签: c# drop-down-menu

当按下 Enter (键13)时,如何关闭下拉列表?

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
        if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '\b')
            e.Handled = true;
        if (e.KeyChar == 13)
            //close open dropdown list
}

1 个答案:

答案 0 :(得分:4)

关闭任何Combobox尝试

  DroppedDown = false;

在您的代码示例中,它可能是

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
        if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '\b')
            e.Handled = true;
        if (e.KeyChar == 13)
            (sender as ComboBox).DroppedDown = false;// <- close opened dropdown list
}

也许更好的方法是保留默认行为,让.net完成它的工作:

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e) {
    if (e.KeyChar < ' ') // <- preserve default behavior for Enter, Esc etc.
      return;

    // Special conditions here
    if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '\b')
      e.Handled = true;
}