Search code examples
c#maxoledb

c# assign the highest id of an access database to a variable


I'm a 100% that the issue I'm about to describe must have got someday an answer. But I haven't been clever enough to find it out in stackoverflow. So, sorry guys to ask again. But if you have a link for someone's post who got that issue resolved, I'll take it !

Here's a piece of the c# code I'm struggling with for the moment:

OleDbConnection cnx = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\MyAccessDB.accdb");

string strReq = "SELECT ISNULL(MAX(CAST(FIELD_ID as Int)),0) + 1 FROM TBL_TABLE";
cnx.Open();
OleDbCommand cmd = new OleDbCommand(strReq, cnx);
OleDbDataReader dr = cmd.ExecuteReader();

if (dr.Read())
{
   int intId = (int)dr["FIELD_ID"];
}

cmd.Dispose();
cnx.Close();

That piece of code is supposed to assign the max value + 1 to the FIELD_ID of the access table TBL_TABLE. But I have an issue on line #5 !!! I'm really out of ideas... Can anyone please help ?


Solution

  • Thanks again to Alex K & Nikki9696, here's the good working code:

    OleDbConnection cnx = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\MyAccessDB.accdb");
    string strReq = "SELECT MAX(FIELD_ID) AS ID FROM TBL_TABLE";
    cnx.Open();
    OleDbCommand cmd = new OleDbCommand(strReq, cnx);
    OleDbDataReader dr = cmd.ExecuteReader();
    
    if (dr.Read())
    {
        int intId = (int)dr["ID"];
    }
    
    cmd.Dispose();
    cnx.Close();