Cómo obtener el índice de elementos de ListBox

Currently using a Listbox and contextMenuStrip, after item right clicked how can the item's index be retrieved from the Listbox ?

Mi función:

private void contextMenuStripOption1_Click(object sender, EventArgs e)
{
    if (listBoxFiles.SelectedIndex == -1)
    {
        return;
    }

    Point ptCursor = Cursor.Position;
    int itemIndex = listBoxFiles.IndexFromPoint(ptCursor);
}

Delete function:

private void contextMenuStripDelete_Click(object sender, EventArgs e)
{
    if (listBoxFiles.SelectedIndex == -1)
    {
        return;
    }

    listBoxFiles.Items.RemoveAt(listBoxFiles.SelectedIndex);
}

preguntado el 09 de marzo de 12 a las 13:03

Why can't you just use listBoxFiles.SelectedIndex? -

2 Respuestas

Do not assign the ContextMenuStrip to the ListBox; instead open it programmatically after you have determined the selected index

int _selectedIndex;

private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right) {
        _selectedIndex = listBox1.IndexFromPoint(e.Location);
        if (_selectedIndex == -1) {
            return;
        }
        contextMenuStrip1.Show(listBox1.PointToScreen(e.Location));
    }
}

ACTUALIZACIÓN:

Now you can access the index from the menu item clicks

private void contextMenuStripDelete_Click(object sender, EventArgs e)
{
    listBoxFiles.Items.RemoveAt(_selectedIndex);
}

No need to recalculate the selected index and to test for -1. The context menu is not opened at all if the index is -1.

respondido 10 mar '12, 17:03

i didn't understand this: open it programatically after you have determined the selected index, how can i do it ? - falukky

OK so now i can reach to the item's index, and i have in my Listbox menu 2 option one of them is Delete (see my update), in the listBoxFiles_MouseUp function i can reach to the item index but how can i do it from the contextMenuStripDelete_Click function ? - falukky

My code sets the member variable _selectedIndex. This one can be accessed in the menu clicks. - Olivier Jacot Descombes

Use the container control: listBoxFiles.Items.IndexOf(listBoxFiles.SelectedItem)

respondido 09 mar '12, 13:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.