使用复选框从datagrid中删除多行

时间:2015-11-30 15:31:15

标签: c# wpf datagrid

我使用代码通过使用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();
        }
    }
}

以上代码适用于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;
}

以上代码在删除行中的多行时会出错

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

“值不能为空。\ r \ nParameter name:element”

1 个答案:

答案 0 :(得分:0)

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