0

I've create a ContexMenu, and the option allow the user to clear the all item in the DataGrid. All working so good, but I want to optimize the algorithm with one method, in particular I want do this:

  1. User go in one of three DataGrid and press right mouse button, delete the option in this table

  2. A method starting the method, this method should do this:

    • Check which table has fired the events, get the DataGrid name and delete all rows of the DataGrid that have fired the events. This is my code XAML CODE:

      ContextMenu x:Key="Squadre_ContextMenu">
          <MenuItem Header="Pulisci Tabella" Click="ClearTable_Click">
          </MenuItem>
      </ContextMenu>
      

C# CODE method calling:

private void ClearTable_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine(((DataGrid)sender).Name.ToString()); //exception returned...
        //datagrid.ClearValue();
    }

and in a class I've the property function:

 public static void removeRows(DataGrid name passed by parameter)
    {
        var grid = parameter passed;
        var mygrid = parameter passed;

        if (grid.SelectedIndex >= 0)
        {
            for (int i = grid.SelectedItems.Count - 1; i >= 0; i--)
            {
                mygrid.Items.Remove(grid.SelectedItems[i]);
            };
        }

        grid = mygrid;
    }

NB: datagrid variable is an instance of the class DataGrid datagrid = new DataGrid(); this class contains the function for delete all the rows.

Bender
  • 523
  • 6
  • 21

1 Answers1

0

Why bother passing the name of the grid? Why not just pass the grid itself to the function and operate on it that way?

    private void ClearDataGrid(DataGrid aDataGrid)
    {
        // clear aDataGrid's contents here
    }

Just call the function, and pass the DataGrid you want to clear to it.

You can use the following information to determine what control was clicked on:

Determine what control the ContextMenuStrip was used on

Community
  • 1
  • 1
Dr. Cogent
  • 76
  • 1
  • 8