WPF与datagrid删除所选项目

时间:2015-10-15 13:31:21

标签: c# wpf sqlite datagrid

我有一个从SQLite表中填充的Datagrid

Connect();
mAdapter = new SQLiteDataAdapter("SELECT * FROM clients", mConn);
mTable = new DataTable();
mAdapter.Fill(mTable);
dataGrid.ItemsSource = mTable.DefaultView;
mConn.Close();

我可以删除一个选定项目,但是如何根据其ID删除选定项目

private void dataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Delete)
        {
            if (dataGrid.SelectedItem == null)
                return;
            DataRowView rowView = (DataRowView)dataGrid.SelectedItem;
            Connect();
            using (SQLiteCommand mCmd = new SQLiteCommand("DELETE FROM clients WHERE ID=" + rowView["ID"], mConn))
            {
                mCmd.ExecuteNonQuery();
            }
            mAdapter.Update(mTable);
            mConn.Close();
        }
    }    

2 个答案:

答案 0 :(得分:1)

正如user2946329所说,你的代码应该可行。我想如果你需要删除多个项目,你需要更多的按钮,你必须设置每个按钮通过单独的变量删除,或者你可以通过实际的SQL数据循环它们,例如

string a = select name, from tbl where name = "Ahmed" 
string b =       select name, from tbl where name = "Ahmed"etc) 

然后只是

SQLiteCommand mCmd = new SQLiteCommand("DELETE FROM clients WHERE ID=" + a + b, mConn))
        {
            mCmd.ExecuteNonQuery();
        }

答案 1 :(得分:1)

看起来您想使用原始查询来删除项目。在这种情况下,要访问DataGrid上的选定项,请使用属性SelectedItems。您可以删除每个查询或1个查询中的项目块,以下是使用1个查询删除每个查询的代码:

if (e.Key == System.Windows.Input.Key.Delete) {
        if (dataGrid.SelectedItem == null)
            return;
        Connect();
        foreach(var item in dataGrid.SelectedItems.Cast<DataRowView>()) {
           using (var mCmd = new SQLiteCommand("DELETE FROM clients WHERE ID=" + item["ID"], mConn)) {
              mCmd.ExecuteNonQuery();
           }
        }
        mAdapter.Update(mTable);
        mConn.Close();
}

以下是使用1个查询删除项目块的代码:

if (e.Key == System.Windows.Input.Key.Delete) {
        if (dataGrid.SelectedItem == null)
            return;
        Connect();
        const int blockSize = 100;
        var inOperands = dataGrid.SelectedItems
                                 .Select((e,i) => new { 
                                    row = ((DataRowView) e)["ID"], i        
                                  })
                                 .GroupBy(e => e.i / blockSize)
                                 .Select(g => string.Format("({0})", 
                                              string.Join(",", g.Select(o => o.row))));
        foreach(var inOperand in inOperands) {
           using (var mCmd = new SQLiteCommand("DELETE FROM clients WHERE ID IN " + inOperand, mConn)) {
              mCmd.ExecuteNonQuery();
           }
        }
        mAdapter.Update(mTable);
        mConn.Close();
}

顺便说一下,您应该使用SQLiteParameter而不是手动连接值以避免查询注入。