thevan
thevan

Reputation: 10354

How to remove the DataTable's Row without using loops?

I have one datatable which has

DataTable:

         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }

But without loops, How to remove the row based on this condition?

Upvotes: 0

Views: 7399

Answers (4)

KV Prajapati
KV Prajapati

Reputation: 94645

Another option is to use DataView instance.

//Set sort key and order
 DTItem.DefaultView.Sort = "SeqNo";
 DTItem.DefaultView.Delete(DTItem.DefaultView.Find(2));

Upvotes: 0

Tu Tran
Tu Tran

Reputation: 1977

Try this:

DataRow[] rows = DTItem.Select("SeqNo = " + SeqNo);
foreach (DataRow row in rows) {
    DTItem.Rows.Remove(row);
}

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38210

If you are sure that there is only one and definitely one occurrence of the row you can achieve that as following

dt1.Rows.Remove(dt1.Select("SeqNo= 3")[0]);

Upvotes: 0

Paolo Falabella
Paolo Falabella

Reputation: 25844

try

DataRow[] rows = DTItem.Select(" SeqNo = " + SeqNo );
rows[0].Delete();

Upvotes: 2

Related Questions