从数据表中删除行

时间:2013-05-25 20:28:02

标签: c# asp.net

我想从DataTable中删除多条记录 例如 : 在我的情况下PaperId是重复几次。我想删除所有重复记录。

我已编写代码,但循环正在给出错误

        DataSet ds = new DataSet();
        sqlDad.Fill(ds);
        DataTable dt1 = new DataTable();
        ds.Tables.Add(dt1);
        dt1 = ds.Tables[0];
        DataTable dt2 = new DataTable();
        dt2 = dt1;
        List<DataRow> rowsToDelete = new List<DataRow>();

        foreach(DataRow dr in ds.Tables[0].Rows)
        {
            int r = ds.Tables[0].Columns.Count;
            string x =  dr.ItemArray[0].ToString();
            int counter = 0;
            foreach (DataRow dr1 in ds.Tables[0].Rows)
            {

                if (x == dr1.ItemArray[0].ToString())
                {
                    counter++;
                }
                if (counter > 1)
                {
                    rowsToDelete.Add(dr1);
                    foreach (DataRow row in rowsToDelete)
                    {
                        dt2.Rows.Remove(row);
                    }
                    dt2.AcceptChanges();
                    rowsToDelete.Clear();
                }

            }

3 个答案:

答案 0 :(得分:1)

使用DataTable的DefaultView并在不希望重复出现的列上设置排序顺序。您可以遍历行并删除第一行之后的所有行

// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1) 
     return;

// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;

// Set an initial value ( I choose an empty string but you could set to something not possible here 
string x = string.Empty;    

// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
    // If we have a new value, keep it else delete the row
    if(x != dr[0].ToString())
       x = dr[0].ToString();
    else
       dr.Row.Delete();

}
// Finale step, remove the deleted rows
dt1.AcceptChanges();

答案 1 :(得分:1)

试试这个

DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();

答案 2 :(得分:0)

如果您想从 DataTable 中删除整行

试试这个

DataTable dt = new DataTable();  //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
     dt.Rows.Remove(row);