Vishnu Babu
Vishnu Babu

Reputation: 1275

How to check if a Row is already in a DataTable?

I created a DataTable as follows

        DataTable dt2 = new DataTable();            
        DataColumn dc = new DataColumn();

        dc.ColumnName = "Table Allocated";
        dt2.Columns.Add(dc);

        dc = new DataColumn();
        dc.ColumnName = "Capacity";
        dt2.Columns.Add(dc);

Added some Rows to it, Later Created another row like this

            DataRow resRow;
            resRow = dt2.NewRow();

            resRow["Table Allocated"] = "1"
            resRow["Capacity"] = "xx";

How can i check if resRow is already present in the DataTable dt2 aginist all columns in the best way?

Upvotes: 1

Views: 509

Answers (3)

ehh
ehh

Reputation: 3480

One solution can be to use RowFilter:

var dataView = new DataView(dt2);
dataView.RowFilter = string.Format("TableAllocated='{0}', tableAllocatedValue);

Another solution is to use Select

dt.Select(string.Format("TableAllocated='{0}', tableAllocatedValue)); 

Upvotes: 0

Viplock
Viplock

Reputation: 3319

you can try this

    var results = from myRow in dt2.AsEnumerable()
    where myRow.Field<string>("Table Allocated") == resRow["TableAllocated"] 
    && myRow.Field<string>("Capacity")==resRow["Capacity"] 
    select myRow;

if result.count()>0 then there is a row.

Upvotes: 1

waka
waka

Reputation: 3407

You can try something like this:

var rowPresent = dt2.Select("Table Allocated=" + resRow["TableAllocated"] + " AND Capacity = '" + resRow["Capacity"] + "'");

Now you can check if rowPresent contains any values and -if not- add the new row to the DataTable

Upvotes: 0

Related Questions