Saturday, 31 October 2015

Auto Increment Id or Number Using Asp.Net C#

No comments    
categories: , , , ,
Automatically Increment Id or Number

Automatically Increment The Id Value or Number  Using Database in Asp.Net C#.

                            
                          DEMO


                        Download

                     HTML Coding

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
   
       <table><tr><td>
           <asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
           </td><td>
               <asp:Label ID="lblID" runat="server" ForeColor="#FF3399"></asp:Label>
           </td></tr>
           <tr><td>
               <asp:Label ID="Label2" runat="server" Text="Course"></asp:Label>
               </td><td>
                   <asp:TextBox ID="txtCourse" runat="server"></asp:TextBox>
               </td></tr>
           <tr><td></td><td>
               <asp:Button ID="Button1" runat="server" Text="Register" OnClick="Button1_Click" />
               </td></tr>

       </table></div>
    </form>
</body>

</html>
                        C# Coding

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getid();
        }
    }
    protected void getid()
    {
        SqlConnection  con = new SqlConnection (System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());      
        con.Open();
        SqlCommand cmd = new SqlCommand("select MAX (CAST( Id as INT)) from Reg", con);
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd.Read())
        {
            string Value = rd[0].ToString();
            if (Value == "")
            {
                lblID.Text = "1";
            }
            else
            {             
                lblID.Text =rd[0].ToString();
                lblID.Text = (Convert.ToInt64(lblID.Text) + 1).ToString();           
            }      
        }
        con.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into Reg values('"+lblID.Text+"','"+txtCourse.Text+"')", con);
        cmd.ExecuteNonQuery();
        getid();
    }

}





              


















0 comments:

Post a Comment