简体   繁体   English

使用复选框从DataGrid删除多行

[英]Deleting multiple rows from datagrid using checkbox

I am using code to delete multiple rows from datagrid by using checkbox in wpf c#. 我正在使用代码通过使用wpf c#中的复选框从datagrid删除多行。

private void DeleteSelected_Click(object sender, RoutedEventArgs e)
{
    for (int j = 0; j < dgemployee.Items.Count; j++)
    {
        DataGridRow item = (DataGridRow)dgemployee.ItemContainerGenerator.ContainerFromItem(dgemployee.Items[j]);
        CheckBox ckb = (CheckBox)GetVisualChild<CheckBox>(item);
        if (ckb.IsChecked.Value)
        {
            string id = (dgemployee.SelectedCells[1].Column.GetCellContent(item) as TextBlock).Text;
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Database2.mdb";
            OleDbCommand cmd = new OleDbCommand("Delete from employee_registration where ID = " + id + "", con);
            con.Open();
            cmd.ExecuteNonQuery();
            BindGrid();
        }
    }
}

this above code is apply at delete button in wpf c#. 上面的代码适用于wpf c#中的删除按钮。

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

this above code gives error when deleting multiple rows at the line 当删除该行的多行时,以上代码给出错误

//int numVisuals = VisualTreeHelper.GetChildrenCount(parent);

"Value cannot be null.\\r\\nParameter name: element" “值不能为空。\\ r \\ n参数名称:元素”

尝试使用i < numVisuals代替i <= numVisuals希望这会i <= numVisuals帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM