C Sharp get id of last inserted row in MS-Access

private int AddToSuppliersLedger(int supplier_id, string supplier_invoice_id, string from_where, string paid_amount, string total_payment, DateTime payment_date)
        {

            int suppliers_ledgers_id = 0 ;
            //SQL STMT
            string sql = "INSERT INTO suppliers_ledgers(supplier_id,supplier_invoice_id,from_where,paid_amount,total_payment,payment_date) VALUES(@INVOICE,@SUPPLIER,@FROM_WHERE,@PAID,@PAYMENT,@DATE)";
            string sql2 = "SELECT @@Identity";
            cmd = new OleDbCommand(sql, con);

            //ADD PARAMS
            if (paid_amount != "")
            {
                
                cmd.Parameters.AddWithValue("@INVOICE", supplier_id);
                cmd.Parameters.AddWithValue("@SUPPLIER", supplier_invoice_id);
                cmd.Parameters.AddWithValue("@FROM_WHERE", from_where);
                cmd.Parameters.AddWithValue("@PAID", paid_amount);
                cmd.Parameters.AddWithValue("@PAYMENT", total_payment);
                cmd.Parameters.AddWithValue("@DATE", payment_date.ToString());

                //OPEN CON AND EXEC INSERT
                try
                {
                    con.Open();
                    if (cmd.ExecuteNonQuery() > 0)
                    {
                        cmd.CommandText = sql2;
                        suppliers_ledgers_id = (int)cmd.ExecuteScalar();
                        //MessageBox.Show("imhere-" + suppliers_ledgers_id);
                    }
                    con.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    con.Close();
                }
                
            }

            return suppliers_ledgers_id;
        }
Share on Facebook0Tweet about this on Twitter0Share on Google+0Pin on Pinterest0Share on LinkedIn0Share on Reddit0
It's only fair to share...

Add Comment

Required fields are marked *. Your email address will not be published.