简体   繁体   中英

DataTable find or if not found insert row

I have a DataTable dt with 2 columns. First col (call it CustomerId) is unique and doesn't allow nulls. the second one allows nulls and is not unique.

From a method I get a CustomerId and then I would like to either insert a new record if this CustomerId doesn't exist or increment by 1 what's in the second column corresponding to that CustomerId if it exists.

I'm not sure how I should approach this. I wrote a select statement (which returns System.Data.DataRow) but I don't know how to test whether it returned an empty string.

Currently I have:

//I want to insert a new row
if (dt.Select("CustomerId ='" + customerId + "'") == null) //Always true :|
    {
        DataRow dr = dt.NewRow();
        dr["CustomerId"] = customerId; 
    }

If the datatable is being populated by a database. I would recommend making the customerid a identity column. That way when you add a new row it will automatically create a new customerid which will be unique and 1 greater than the previous id (depending on how you setup your identity column)

I would check the row count which is returned from the select statement. Something like

I would also use string.Format...

So it would look like this

var selectStatement = string.Format("CustomerId = {0}", customerId);
var rows = dt.Select(selectStatement);
if (rows.Count < 1){
  var dr = dt.NewRow();
  dr["CustomerId"] = customerId; 
}

This is my method to solve similar problem. You can modify it to fit your needs.

public static bool ImportRowIfNotExists(DataTable dataTable, DataRow dataRow, string keyColumnName)
{
    string selectStatement = string.Format("{0} = '{1}'", keyColumnName, dataRow[keyColumnName]);
    DataRow[] rows = dataTable.Select(selectStatement);
    if (rows.Length == 0)
    {
        dataTable.ImportRow(dataRow);
        return true;
    }
    else
    {
        return false;
    }
}

The Select Method returns an array of DataRow objects. Just check if its length is zero (it's never null ).

By the way, don't write such statements in the code directly as in this example. There's a technique for breaching your code's security called "SQL Injection", I encourage you to read the Wikipedia Article . In brief, an experienced user could write SQL script that gets executed by your database and potentially do harmful things if you're taking customerId from the user as a string. I'm not experienced in database programming, this is just "general knowledge"...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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