Binding DataGrid.DeleteCommand to a button

Mar 25, 2009 at 8:16 AM
Hi,
How do I bind to the DeleteCommand of a DataGrid to a button? I've tried this but it something is wrong - the button gets enabled/disabled as items in the grid are selected / deselected and if I press the button it gets disabled as well, but no items are removed. Removing by pressing the delete button works.

<Window x:Class="GridDeleteTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <toolkit:DataGrid AutoGenerateColumns="False" Name="grid">
            <toolkit:DataGrid.Columns>
                <toolkit:DataGridTextColumn Binding="{Binding Mode=OneWay}" Header="Header" IsReadOnly="True" />
            </toolkit:DataGrid.Columns>
        </toolkit:DataGrid>
        
        <Button Command="toolkit:DataGrid.DeleteCommand" CommandTarget="{Binding ElementName=grid}" Content="Remove"/>
    </StackPanel>
</Window>

Mar 31, 2009 at 10:27 AM
Hi,
I had the same problem, and solved that on this way:
set button property Focusable="False"
Coordinator
Mar 31, 2009 at 8:52 PM
Thank you for reporting this issue; we are investigating and hope to release a fix in a future update.

Alexis
Apr 1, 2009 at 1:12 PM

Hi there, i have a few scripts that might help you on the binding delete to a button, you just put them in a click envent

if (MessageBox.Show(
string.Format("Are you sure you want to permently delete {0}?",
dataGVReport.SelectedItems.Count > 1
? string.Format("{0} records?", dataGVReport.SelectedItems.Count)
: "this record"),
"Verify your request", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
try
{
accessCon = new OleDbConnection();
accessCon.ConnectionString = Common.GetConnectionString();
accessCon.Open();
IList iList = dataGVReport.SelectedItems;
for(int i = 0; i < iList.Count; i++)
{
DataRowView drv = (DataRowView)iList[i]; //get datarowview
int primaryID = (int)drv.Row[0];//get current row's primary id
dtAllBusiness.Rows.Remove(dtAllBusiness.Rows.Find(primaryID));//remove the datarow by finding primaryID
accessCmd = new OleDbCommand(@"DELETE * FROM DailyOperation WHERE Operation_id = " + primaryID, accessCon);
accessCmd.ExecuteNonQuery();  
}
accessCon.Close();
ListProducts(dtAllBusiness); //this is to refresh datagrid again, 

}
catch (Exception ex)
{
CustomMessageBox.Show(this, ex.Message + "... Please Contact Support Immediately!!!", title, MessageBoxButton.OK, (MessageBoxImage)Enum.Parse(typeof(MessageBoxImage), "Warning"));
}
}

May 12, 2009 at 10:22 AM

I had this issue as well.

@miki28: Thanks for the quick fix, seems to work!

@totolwang: Dude, do you really put SQL statements in your event handlers? :)