Europa
Europa

Reputation: 1284

How to find value of Datagrid row that I have pressed 'DELETE' key on using WPF

When pressing "DELETE" key on my keyboard I can remove items from a Datagrid. However, it is not removed from the SQLite database. I need to get the value or row number of the item that the user has pressed DELETE on in order to delete it from SQLite database.

XAML

<DataGrid x:Name="dataGridKeywords" PreviewKeyDown="dataGridKeywords_PreviewKeyDown" DockPanel.Dock="Top" HorizontalAlignment="Left" Width="Auto" Margin="5,0,5,0" VerticalAlignment="Top" FontSize="15" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" />

C#

private void dataGridKeywords_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var grid = (DataGrid)sender;

        if (grid.SelectedItems.Count > 0)
        {
            String value = "???";
            String query = "DELETE FROM table WHERE value='" + value + "'";
        }
    }
} // dataGridKeywords_PreviewKeyDown

Update, this is how I add items to my DataGrid:

private void loadKeywordListKeywords(){
    // Create data table
    DataTable dt = new DataTable();
    DataColumn dataColumn1 = new DataColumn("Keyword", typeof(string));
    DataColumn dataColumn2 = new DataColumn("Regex", typeof(string));
    dt.Columns.Add(dataColumn1);
    dt.Columns.Add(dataColumn2);

    // Connect to general db
    DBAdapterSQLite dbSoftware = new DBAdapterSQLite(config.databasePath, config.databaseFile, true);
    dbSoftware.open();

    // Fetch all keywords
    query = "SELECT keyword_id, keyword_value, keyword_is_regex FROM keyword_lists_keywords WHERE keyword_list_id=" + this.currentKeywordListId;
    using SQLiteDataReader reader = dbSoftware.queryRows(query);
    while (reader.Read())
    {
        int keywordId = reader.GetInt32(0);
        String keywordValue = reader.GetString(1);
        int keywordIsRegex = reader.GetInt32(2);


        // Add to Grid
        DataRow dataRow = dt.NewRow();
        dataRow[0] = keywordValue; 
        dataRow[1] = keywordIsRegex;

        // Add to list
        dt.Rows.Add(dataRow);
    }
    reader.Close();

    // Close db
    dbSoftware.close();

    // Add data to data grid
    dataGridKeywords.ItemsSource = dt.DefaultView;
    dataGridKeywords.Visibility = Visibility.Visible;
 } // loadKeywordListKeywords

Upvotes: 0

Views: 165

Answers (1)

BionicCode
BionicCode

Reputation: 28968

The DataGrid supports deletion of rows by default. It also exposes a routed DataGrid.DeleteCommand.

Pressing the Del key will execute the DataGrid.DeleteCommand too and automatically removes the currently selected row(s) from the DataGrid.

All you have to do is to subscribe to the CommandManager.PreviewExecuted attached event:

<DataGrid CommandManager.PreviewExecuted="DeleteSqlRow_OnPreviewExecuted">
  <DataGrid.Columns>
    <DataGridTemplateColumn>

      <!-- Add a delete button column which uses the integrated delete command -->
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <Button Content="X" Command="{x:Static DataGrid.DeleteCommand}" />
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

Handle the removed items:

private void DeleteSqlRow_OnPreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
  if (e.Command == DataGrid.DeleteCommand)
  {
    var multiSelector = e.Source as MultiSelector;

    // In case the data source of the DataGrid is a DataTable, 
    // the selected items are DataRowView instances.
    // Otherwise the selected items are the the items contained in the DataGrid.ItemsSource
    IEnumerable<DataRowView> deletedItems = multiSelector.SelectedItems.Cast<DataRowView>();

    foreach (DataRowView deletedItem in deletedItems)
    {
      var value = deletedItem["Keyword"];
    }
  }
}

Upvotes: 1

Related Questions