Today I am going to show you how to generate id in C# using MS Access Database

Let’s start with create a new windows form. We need one Label, one TextBox one button and one GridView.

The code is shown below:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Data.OleDb;
  10. namespace idgenerator
  11. {
  12. public partial class Form1 : Form
  13. {
  14. OleDbConnection connectiondb = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\C# Cor\database\mydatabase.accdb;Persist Security Info=False");
  15. OleDbCommand com;
  16. string str;
  17. public Form1()
  18. {
  19. InitializeComponent();
  20. new_id();
  21. showdata();
  22. }
  23. private void Form1_Load(object sender, EventArgs e)
  24. {
  25. }
  26. private void new_id()
  27. {
  28. if (connectiondb.State == ConnectionState.Closed)
  29. {
  30. connectiondb.Open();
  31. }
  32. str = "select max(admin_create_id) from tbl_user";
  33. com = new OleDbCommand(str, connectiondb);
  34. com.CommandType = CommandType.Text;
  35. Int32 max = (Int32)com.ExecuteScalar();
  36. label3.Text = (max + 1).ToString();
  37. connectiondb.Close();
  38. }
  39. private void button1_Click(object sender, EventArgs e)
  40. {
  41. if (connectiondb.State == ConnectionState.Closed)
  42. {
  43. connectiondb.Open();
  44. }
  45. str = "insert into tbl_user (admin_create_id,sName) values (@admin_create_id,@sName)";
  46. com = new OleDbCommand(str, connectiondb);
  47. com.Parameters.AddWithValue("@admin_create_id", label3.Text);
  48. com.Parameters.AddWithValue("@sName", textBox2.Text);
  49. com.ExecuteNonQuery();
  50. connectiondb.Close();
  51. MessageBox.Show("Records Successfuly Inserted");
  52. showdata();
  53. new_id();
  54. }
  55. private void showdata()
  56. {
  57. if (connectiondb.State == ConnectionState.Closed)
  58. {
  59. connectiondb.Open();
  60. }
  61. string strSql = "Select admin_create_id,sName from tbl_user";
  62. OleDbCommand cmd = new OleDbCommand(strSql, connectiondb);
  63. cmd.CommandType = CommandType.Text;
  64. OleDbDataAdapter da = new OleDbDataAdapter(cmd);
  65. DataTable dt = new DataTable();
  66. da.Fill(dt);
  67. dataGridView1.DataSource = dt;
  68. connectiondb.Close();
  69. }
  70. }
  71. }

Result
Thanks.!!