如何在wpf datagrid中删除所选行(使用复选框) [英] How to delete selected rows (using checkbox) in wpf datagrid

查看:914
本文介绍了如何在wpf datagrid中删除所选行(使用复选框)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WPF DataGrid是:

 < dg:DataGrid Name =datagrid1Grid.RowSpan =1VerticalAlignment =StretchGrid.ColumnSpan =2> 

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

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

还有动态我正在将数据填充到datgrid.In xaml.cs文件中,我写下面给出从数据网格中删除所选行的代码,但是在行上抛出错误

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

所以请看看下面给出的代码,我写的是这样做的。 p>

  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];
//删除行更新到数据库
}
}
}
static T GetVisualChild< T>(Visual parent)其中T:Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent); (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;
}

请让我知道是不是错了。

解决方案

这是我将如何做到这一点。实现继承INotifyPropertyChanged的类的ObservableCollection。 INotifyPropertyChanged将用于我们想要更新集合中的项目。



首先为GridView的xaml

 < DataGrid x:Name =gvMainAutoGenerateColumns =TrueHorizo​​ntalAlignment =Left
VerticalAlignment =TopHeight =300Width =300> ;< / DataGrid>

我们的课程类别

  public class MyClass:INotifyPropertyChanged 
{
public event PropertyChangedEventHandler PropertyChanged;

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

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));
}
}
}

接下来的WPF窗口



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

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

测试添加,更改,删除集合中的项目

  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)
{
//使用List来使用.ForEach较少的代码来写,看起来更清洁
列表< MyClass> remove = gridData.Where(x => x.LastName.Equals(Smith))ToList();
remove.ForEach(x => gridData.Remove(x));
}

您要做的任何更改都将使用gridData完成。


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.

解决方案

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.

这篇关于如何在wpf datagrid中删除所选行(使用复选框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆