简体   繁体   English

数据表/数据行如果存在更新其他插入

[英]Datatable/Datarow If Exists Update Else Insert

Trying to find an answer to this has proven difficult, since all the answers deal with SQL! 试图找到答案已经证明是困难的,因为所有的答案都与SQL有关!

I have a Datatable TestTable . 我有一个Datatable TestTable In this DataTable I have three columns, ID , ValueX , and ValueY . 在这个DataTable中,我有三列, IDValueXValueY 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. 当我向此数据表添加新记录时,我正在尝试创建一个插入方法,以查看记录是否存在,但无法使用Select语句来使用多个字段。 In my situation, I need to see if the Datatable contains a record that equals ID and ValueX, if it does, update. 在我的情况下,我需要查看Datatable是否包含等于ID和ValueX的记录,如果是,则更新。 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);
}

You can use the Find method 您可以使用Find方法

DataRowCollection.Find Method (Object[]) DataRowCollection.Find方法(Object [])

Gets the row that contains the specified primary key values. 获取包含指定主键值的行。

to look for a specific DataRow . 寻找特定的DataRow Note that your DataTable has to have a appropriate primary key. 请注意,您的DataTable必须具有适当的主键。

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};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM