日期:2014-05-18  浏览次数:21050 次

删除DataTable中除指定行以外的行
假设有一个DataTable的数据如下所示:

ID NAME MEMO
1 AA 1111
2 BB 2222
3 CC 3333
4 DD 4444
5 EE 5555
6 FF 6666
7 GG 7777
.. .. ....

要删除ID包含在集合(1,3,5,6,......)中以外的行,
也就是说保留ID包含在集合(1,3,5,6,......)中的行,其他的行删除.

------解决方案--------------------
dt.Rows[i].Delete()
i你知道的
------解决方案--------------------
DELETE FROM table WHERE id NOT IN (...)
------解决方案--------------------
你可以用DataView过滤!就可以只看你要的数据!
C# code


private void BindDataGrid()
{
    DataTable table = new DataTable();

    // Insert code to populate a DataTable with data.

    // Bind grid to DataTable.
    dataGrid1.DataSource = table;
}

private void ChangeRowFilter()
{
    DataTable gridTable = (DataTable) dataGrid1.DataSource;

    // Set the RowFilter to display a company names that 
    // begin with A through I..
    gridTable.DefaultView.RowFilter = "CompanyName < 'I'";
}

------解决方案--------------------
探讨
DELETE FROM table WHERE id NOT IN (...)

------解决方案--------------------
DELETE FROM table WHERE id NOT IN (1,3,5,6,......)
这个就可以
------解决方案--------------------
C# code

private void button1_Click(object sender, EventArgs e)
{
    string[] ids="1,3,5".Split(',');
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("NAME");
    dt.Columns.Add("MEMO");
    dt.Rows.Add("1", "AA", "1111");
    dt.Rows.Add("2", "BB", "1111");
    dt.Rows.Add("3", "CC", "1111");
    dt.Rows.Add("4", "DD", "1111");
    dt.Rows.Add("5", "EE", "1111");

    for (int i = dt.Rows.Count - 1; i >= 0; i--)
    {
        if (Array.IndexOf(ids,dt.Rows[i]["id"].ToString())>=0)
        {
            dt.Rows[i].Delete();
         }
    }
}

------解决方案--------------------
view.Table = DataSet1.Tables["Suppliers"];
view.AllowDelete = true;
view.AllowEdit = true;
view.AllowNew = true;
view.RowFilter = "ID NOT IN '1,2,3,4,5,6'";

------解决方案--------------------
C# code

view.Table = DataSet1.Tables["Suppliers"];
  view.AllowDelete = true;
  view.AllowEdit = true;
  view.AllowNew = true;
  view.RowFilter = "ID NOT IN '1,2,3,4,5,6'";

------解决方案--------------------
C# code

            DataTable dt = new DataTable("Data");
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            dt.Rows.Add(1, "小三1");
            dt.Rows.Add(2, "小三2");
            dt.Rows.Add(3, "小三3");
            dt.Rows.Add(4, "小三4");
            dt.Rows.Add(5, "小三5");
            dt.Rows.Add(6, "小三6");
            dt.Rows.Add(7, "小三7");

            //保留的行
            string[] ids = { "1", "3", "5" };
            // 获取删除的行集合
            DataRow[] drsDel = dt.Select(string.Format("Id not in ({0})", string.Join(",", ids)));
            //直接在集合中删除
            foreach (DataRow drDel in drsDel)
            {
                dt.Rows.Remove(drDel);
            }