Pregunta

I've been programming an application with C#. The app has multiple listviews and I'd like to make it possible to copy text from any of them with as little code as possible. Currently my copy menu only works with one of the listviews. Here is my code:

Code to copy data:

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    //ListView listView = sender as ListView; <---- this didnt work
    if (listViewOrders.SelectedItems.Count >= 1)
    {
        Clipboard.Clear();
        StringBuilder buffer = new StringBuilder();

        // Build the data row by row
        foreach (ListViewItem item in listViewOrders.SelectedItems)
        {
            buffer.Append(item.SubItems[0].Text.ToString());
            buffer.Append("\n");
        }
        Clipboard.SetText(buffer.ToString());
    }
}

Code to create copy menu when clicked:

private void listViewOrders_MouseClick(object sender, MouseEventArgs e)
{
    ListView listView = sender as ListView;

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        ListViewItem item = listView.GetItemAt(e.X, e.Y);

        if (item != null)
        {
            item.Selected = true;
            contextMenuStrip1.Show(listView, e.Location);
        }
    }
}
¿Fue útil?

Solución

In listViewOrders_MouseClick assign the listview to contextMenuStrip1.Tag:

private void listViewOrders_MouseClick(object sender, MouseEventArgs e)
{
    ListView listView = sender as ListView;

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        ListViewItem item = listView.GetItemAt(e.X, e.Y);

        if (item != null)
        {
            item.Selected = true;
            contextMenuStrip1.Tag = listView;
            contextMenuStrip1.Show(listView, e.Location);
        }
    }
}

and then get it back in toolStripMenuItem1_Click:

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    ListView listView = (sender as ToolStripItem).Owner.Tag as ListView;
    //ListView listView = (sender as Control).Tag as ListView;
    if (listViewOrders.SelectedItems.Count >= 1)
    {
        ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top