事实证明,尝试找到答案很困难,因为所有答案都与SQL有关!
我有一个数据表TestTable.在此数据表中,我有三列,ID,ValueX和ValueY.当我向该数据表添加新记录时,我试图创建一个插入方法来查看记录是否存在,但无法获取Select语句以使用多个字段.在我的情况下,我需要查看数据表是否包含等于ID和ValueX的记录(如果存在),则更新.否则,将新记录添加到数据表中.
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);
}
解决方法:
您可以使用Find
method
DataRowCollection.Find Method (Object[])
Gets the row that contains the specified primary key values.
寻找特定的DataRow.请注意,您的DataTable必须具有适当的主键.
例:
// 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};