Saturday 1 September 2018

Auto Increment Id or Number Using Asp.net C#


Automatically increasing Id or Number and save the data in the Database using Asp.net C#


HTML Coding

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Auto Increment Id or Number</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();
        txtCourse.Text = "";
        getid();
    }
}

Create the table




No comments:

Post a Comment