aaps k
aaps k

Reputation: 13

How do I delete selected grid row programmatically

I want to add and delete rows dynamically in the datagrid. This is the code that I use to add rows by using the click property of an add button:

DataTable dt = new DataTable();
        private void AddRow(object sender, RoutedEventArgs e)
        {
            DataRow dr = dt.NewRow();

            DataGrid1.ItemsSource = dt.DefaultView;
            dt.Rows.Add(dr);

        }

similarly I want to create a delete button and delete the selected row how can I do that?

Upvotes: 1

Views: 2973

Answers (2)

Nemanja Banda
Nemanja Banda

Reputation: 861

You need to remove element from your data source, which is in this case DataTable dt. Just use the following code to remove selected row from the table:

private void DeleteRow(object sender, RoutedEventArgs e)
{
    dt.Rows.RemoveAt(DataGrid1.SelectedIndex);
}

Upvotes: 2

Muds
Muds

Reputation: 4116

You can bind your delete button to a command with a parameter. The parameter will be your Grid.SelectedItem

then when you handle command you will have selected item, do whatever you wish to do with it.

see here for command parameters.

Upvotes: 0

Related Questions