5
Answers

increment ID automatically by adding +1

I'm developing a simple application to insert values to ms access database but I need to make event ID as automated field by get maximum value from the column and add +1 to insert the new value
 
 
  1. OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\zoom\Desktop\TRAVIL IN OMAN PROJECT - Copy\WebApplication1\WebApplication1\App_Data\travilinoman.MDB.mdb");  
  2.        con.Open();  
  3.        OleDbCommand cmd = new OleDbCommand("select MAX(ID)+1 from event", con);  
  4.        OleDbDataReader dr = cmd.ExecuteReader();  
  5.        TextBox1.Text = dr.ToString();  
  6.            con.Close();  
 the textboxis showing this result : System.Data.OleDb.OleDbDataReader
 
how can I convertit to the acctual value (int) ??? 

Answers (5)

2
Photo of Amit Gupta
NA 16.5k 25.7k 7y
If you have only one result then its better to use ExecuteScalar() function.
  1. OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\zoom\Desktop\TRAVIL IN OMAN PROJECT - Copy\WebApplication1\WebApplication1\App_Data\travilinoman.MDB.mdb");    
  2.        con.Open();    
  3.        OleDbCommand cmd = new OleDbCommand("select MAX(Nz(ID,0))+1 from event", con);    
  4.        TextBox1.Text = Convert.ToString(cmd.ExecuteScalar());  
  5.            con.Close();    
 We are using Nz function here, when ID is null then it will return 0 instead of null
 
 
Accepted
1
Photo of Sulieman Alkatib
NA 56 1.8k 7y
work well
 
thanks master Amit 
 
 
 
 
  1. con.Open();      
  2.       OleDbCommand cmd = new OleDbCommand("select MAX(Nz(ID,0))+1 from event", con);      
  3.       TextBox1.Text = Convert.ToString(cmd.ExecuteScalar());    
  4.           con.Close();      
1
Photo of Khaja Moizuddin
NA 6.3k 206.6k 7y
Why dont you use identity column to increment the row number by 1 instead of doing it from Code.
1
Photo of Sulieman Alkatib
NA 56 1.8k 7y
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: No data exists for the row/column.
 
 
 
not working
 
 
I have this code on VB.net but I could not convert it to C
 
 
 
  1. Dim conn As New SqlConnection("Data Source=xp-pc;Initial Catalog=HR;Integrated Security=True")  
  2. Dim cmd As New SqlCommand("select MAX(LID)+1 from Letters ", conn)  
  3.   
  4. Dim sql As String = "select MAX(LID)+1 from Letters "  
  5.   
  6. conn.Open()  
  7.   
  8. Dim lid As Int32 = Convert.ToInt32(cmd.ExecuteScalar)  
  9. conn.Close()  
  10. TextBox1.Text = lid  
1
Photo of Bharath Peggem
NA 696 10.3k 7y
Hi Sulieman,
 
Try this 
 
   TextBox1.Text = dr[0];
 
Thanks,
Bharath Peggem