【问题标题】:Deleting multiple rows from datagrid using checkbox使用复选框从数据网格中删除多行
【发布时间】:2015-11-30 15:31:15
【问题描述】:

我正在使用代码通过 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\n参数名称:元素”

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    尝试使用i &lt; numVisuals 而不是i &lt;= numVisuals 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2018-03-09
      • 2014-05-27
      • 2015-03-18
      • 2023-04-04
      • 2014-06-20
      • 1970-01-01
      相关资源
      最近更新 更多