简体   繁体   中英

Deleting multiple rows from datagrid using checkbox

I am using code to delete multiple rows from datagrid by using checkbox in wpf c#.

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#.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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