How to delete selected rows (using checkbox) in wpf datagrid

孤者浪人 提交于 2019-12-08 13:35:10

问题


My WPF DataGrid is:

<dg:DataGrid Name="datagrid1"  Grid.RowSpan="1"  VerticalAlignment="Stretch" Grid.ColumnSpan="2">

    <dg:DataGrid.Columns >
        <dg:DataGridTemplateColumn>
            <dg:DataGridTemplateColumn.Header>
                <CheckBox Content=" Slect All" x:Name="headerCheckBox" />
            </dg:DataGridTemplateColumn.Header>
            <dg:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox Name="chkSelectAll" Margin="45 2 0 0"
      IsChecked="{Binding IsChecked, ElementName=headerCheckBox, 
                          Mode=OneWay}" />
                </DataTemplate>
            </dg:DataGridTemplateColumn.CellTemplate>
        </dg:DataGridTemplateColumn>

    </dg:DataGrid.Columns>
</dg:DataGrid>

Also Dynamicaly I am populating the data to the datgrid.In xaml.cs file I written the below given code for deleting the selected row from the data grid but it throwing the error at line

DataGridRow item =(DataGridRow) datagrid1.ItemContainerGenerator.ContainerFromItem(datagrid1.Items[j]);

So Please have a look in to the below given code which I written for doing the same.

   private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        for (int j = 0; j < datagrid1.Items.Count; j++)
        {
            DataGridRow item =(DataGridRow) datagrid1.ItemContainerGenerator.ContainerFromItem(datagrid1.Items[j]);
            CheckBox ckb = (CheckBox)GetVisualChild<CheckBox>(item);
            if (ckb.IsChecked.Value)
            {
                DataRowView drv = (DataRowView)datagrid1.Items[j];
               //delete the row- updating to the database
            }
        }
    }
    static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    } 

Please let me know if am wrong.


回答1:


Here is how I would do this. Implement an ObservableCollection of your class that inherits INotifyPropertyChanged. INotifyPropertyChanged will be used in case we want to update items in the collection.

First the xaml for the GridView

<DataGrid x:Name="gvMain" AutoGenerateColumns="True" HorizontalAlignment="Left"
        VerticalAlignment="Top" Height="300" Width="300"></DataGrid>

Our class of items

public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string firstName { get; set; }
    private string lastName { get; set; }

    public string FirstName
    {
        get 
        {
            return firstName;
        }
        set
        {
            firstName = value;
            PropertyChangedEvent("FirstName");
        }
    }

    public string LastName
    {
        get
        {
            return lastName;
        }
        set
        {
            lastName = value;
            PropertyChangedEvent("LastName");
        }
    }

    private void PropertyChangedEvent(string propertyName)
    {

        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Next the WPF window

public ObservableCollection<MyClass> gridData { get; set; }

public MainWindow()
{
    InitializeComponent();
    gridData = new ObservableCollection<MyClass>();
    gvMain.ItemsSource = gridData;
}

Test to add, change, delete items in the collection

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    gridData.Add(new MyClass() { FirstName = "John", LastName = "Smith"  });
}

private void btnChange_Click(object sender, RoutedEventArgs e)
{
    gridData[0].FirstName = "Meow Mix";
}

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    //using List to use .ForEach less code to write and looks cleaner to me
    List<MyClass> remove = gridData.Where(x => x.LastName.Equals("Smith")).ToList();
    remove.ForEach(x => gridData.Remove(x));
}

Any changes you want to make will be done with gridData.



来源:https://stackoverflow.com/questions/25045572/how-to-delete-selected-rows-using-checkbox-in-wpf-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!