Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatable/Datarow If Exists Update Else Insert

Tags:

c#

sql

datatable

Trying to find an answer to this has proven difficult, since all the answers deal with SQL!

I have a Datatable TestTable. In this DataTable I have three columns, ID, ValueX, and ValueY. As I add new records to this datatable, I am trying to make an insert method that looks to see if the record exists, but cannot get a Select statement to use multiple fields. In my situation, I need to see if the Datatable contains a record that equals ID and ValueX, if it does, update. Otherwise, add the new record to the datatable.

public void Insert(string ID, string ValueX, string ValueY)
{
DataRow dr = TestTable.NewRow();
dr["ID"] = ID;
dr["ValueX"] = ValueX
dr["ValueY"] = ValueY;
TestTable.Rows.Add(dr);
}
like image 490
user3010406 Avatar asked Mar 26 '14 15:03

user3010406


1 Answers

You can use the Find method

DataRowCollection.Find Method (Object[])

Gets the row that contains the specified primary key values.

to look for a specific DataRow. Note that your DataTable has to have a appropriate primary key.

Example:

// create Table with ID, ValueX, ValueY
var table1 = new DataTable();
var id = table1.Columns.Add("ID");
var x = table1.Columns.Add("ValueX");
var y = table1.Columns.Add("ValueY");

// set primary key constain so we can search for specific rows
table1.PrimaryKey = new[] {id, x};

// some sample data
table1.Rows.Add(new Object[] {1, 1, 100});
table1.Rows.Add(new Object[] {2, 2, 200});

// find the row with key {1, 1} and update it, if it exists
// else you would want to create a new row
var exisiting = table1.Rows.Find(new Object[] {1, 1});
if (exisiting != null)
    exisiting.ItemArray = new object[] {1, 1, 9999};
like image 132
sloth Avatar answered Sep 30 '22 14:09

sloth