简体   繁体   中英

On C# WinForm ListBox how to clear the selection of multiple items with a key pressed?

I'm trying to clear the selection of all items in a WinFom ListBox when the escape key is pressed.

I created a KeyPress event handler in order to catch the event. It works when only one item is selected, but when multiple items are selected the event never triggers, . Any idea of what is happening?

Thanks in advance.

Here I attached my event handler:

private void EscapeKeyPressed(object sender, KeyPressEventArgs e)
    {
        try
        {
            if (e.KeyChar == (char)Keys.Escape)
            {
                switch (sender.GetType().GetProperty("Name").GetValue(sender, null).ToString())
                {
                    case "LineLB":
                        LineLB.ClearSelected();
                        break;
                    case "ApplicationLB":
                        ApplicationLB.ClearSelected();
                        break;
                    default:
                        break;
                }
            }
        }
        catch(Exception ex) { MessageBox.Show(ex.Message); }

--20150526--

Thanks all you guys for your comments and suggestions. It was a focus problem as some of you mentioned before. I add a line of code in the SelectedIndexChange event handler, and here the comparison.

Before

private void LineLB_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (LineLB.SelectedItems.Count > 1)
                ClearControlsFromPanel(PanelUser);
            else{
                   ...

After

    private void LineLB_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (LineLB.SelectedItems.Count > 1){
                ClearControlsFromPanel(PanelLine);
                LineLB.Focus();
            }
            else{
                   ...

这是由于在与其他ListBox一起使用时将焦点放在一个ListBox上,因此需要使用Form的KeyPress事件而不是ListBox。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM