Home > Mobile >  C#: Ignore PreviewKeyDown on editing of ListViewItem [closed]
C#: Ignore PreviewKeyDown on editing of ListViewItem [closed]

Time:09-17

C#, WinForms: I can't find any help using google (c# PreviewKeyDown bypass/ignore/edit listvviewitem...), so I would like to ask you for help. Is there any way, how to process PreviewKeyDown in ListView, but ignore it during ListViewItem editing?

I have a ListView in my Form. If user presses "Delete" key, I want to delete an item, so I have an Event handler PreviewKeyDown on the ListView where I evaluate pressed key. Thinks go good.

But now I want to allow user to edit text in the ListViewItem. If users presses F2, I fire BeginEdit();
ListView1.SelectedItems[0].BeginEdit();

Still OK. The Item switches to edit mode and user can rewrite the text. But if user presses "Delete" key, he/she expect the text will be deleted. But because the key is handled by the PreviewKeyDown event handler, the text is not affected.

I tried to create a variable isListViewItemEdited which I set to true in BeforeLabelEdit, but it didn't help. The variable is set to true, the line with e.KeyCode == Keys.Delete is skipped, but the selected text in ListViewItem is not affected.

    private void ListView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (!isListViewEdited)
        {
            if (e.KeyCode == Keys.Delete)
            {
                ...
            }
        }...

Is there any way, how to process PreviewKeyDown in ListView, but ignore it during ListViewItem editing?

CodePudding user response:

Don't use preview key down but use key down. When editing the handle the event.

CodePudding user response:

I think this code would help you:

Enabling ListView Edit Items:

 listView1.LabelEdit = true;

Delete for ListView

 ListViewItem get= new ListViewItem();
           foreach(var item in listView1.SelectedItems)
            {
                get =(ListViewItem)item;
            }
            if (e.KeyCode == Keys.Delete)
            {
                listView1.Items.Remove(get);
            }

Delete for ListBox:

int getindex = listBox1.SelectedIndex;
                if (e.KeyCode == Keys.Delete)
                {
                    listBox1.Items.RemoveAt(getindex);
                }
  • Related