Auto Increment id in c#.net


Auto-increment allows a unique number to be generated when a new record is inserted into a table. Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.We are crate autoincrement using Classfile.

1) Create Class File give name "function"

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using CrystalDecisions.Shared;


namespace Mahesh
{
 
    class function
    {  

        //autoid
        public static string id(string strSQL)
        {
            string pi_id = null;

            try
            {

                String userqry = "";
                userqry = strSQL;
                int i = 0;
                SqlCommand cmd = new SqlCommand(userqry, datastore.Connection());
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        pi_id = dr[0].ToString();
                    }
                    if (pi_id.Equals(""))
                    {
                        pi_id = "1";
                    }
                    else
                    {
                        i = Convert.ToInt32(pi_id);
                        i++;
                        pi_id = "" + i;

                    }

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

            return pi_id.ToString().TrimEnd();
        }
}
}

2) Assigen id to textbox

txtid.text= funcation.id("select max(id) from tablename")

1 comments:

Unknown said...

Full Content Auto Increment id in c#.net
Thank you for sharing .
auto id

Post a Comment