Thursday, 31 August 2017

How to add data in datagridview on button click?

Problem Defination : On button click we want to add textbox vales and combo box values into the datagridview and after that when we click on submit button it will have to save into database. the following figure shows the details of it.


In the above figure we use a DataGridview when we click on ADD Medicines Button values from Medicine Name combo box, Batch No text box , medicine Quantity and Rate will have to add into the DataGridView and when we click on the Save button it will save into the Database.

Double Click on the Add Medicines Button and write the following code into it..

 int z, q;
        private void btnAddMedicine_Click(object sender, EventArgs e)
        {
            try
            {
                if (q == 0)
                {
                    dataGridView1.Columns.Add("MedicineID", "MedicineID");
                    dataGridView1.Columns.Add("MedicineName", "MedicineName");
                    dataGridView1.Columns.Add("BatchNumber", "BatchNumber");
                    dataGridView1.Columns.Add("Quantity", "Quantity");
                    dataGridView1.Columns.Add("Rate", "Rate");
                    q++;
                }
                dataGridView1.Rows.Add();
                dataGridView1.Rows[z].Cells[0].Value = Convert.ToInt32(cmbMedicineId.SelectedValue);
                dataGridView1.Rows[z].Cells[1].Value = cmbMedicineId.Text;
                dataGridView1.Rows[z].Cells[2].Value = cmbBatchNo.Text;
                dataGridView1.Rows[z].Cells[3].Value = Convert.ToInt32(txtMedicineQuantity.Text);
                dataGridView1.Rows[z].Cells[4].Value = Convert.ToDouble(txtRate.Text);
                z++;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Firstly , we have to add Columns MedicineID,MedicineName,BatchNumber,Quantity,Rate by following code.

                    dataGridView1.Columns.Add("MedicineID", "MedicineID");
                    dataGridView1.Columns.Add("MedicineName", "MedicineName");
                    dataGridView1.Columns.Add("BatchNumber", "BatchNumber");
                    dataGridView1.Columns.Add("Quantity", "Quantity");
                    dataGridView1.Columns.Add("Rate", "Rate");
Now we have to add rows so following code is used for it.

        dataGridView1.Rows.Add();
                dataGridView1.Rows[z].Cells[0].Value = Convert.ToInt32(cmbMedicineId.SelectedValue);
                dataGridView1.Rows[z].Cells[1].Value = cmbMedicineId.Text;
                dataGridView1.Rows[z].Cells[2].Value = cmbBatchNo.Text;
                dataGridView1.Rows[z].Cells[3].Value = Convert.ToInt32(txtMedicineQuantity.Text);
                dataGridView1.Rows[z].Cells[4].Value = Convert.ToDouble(txtRate.Text);
                z++;








Tuesday, 29 August 2017

what is $(Document).ready() in Jquery ?

$(document).ready() is a Jquery Event.It fires when DOM is loaded and ready to manipulated by script.This is the earliest point in the page load process where the script can access pages HTML dom. This event fires before the images,css etc are fully loaded.

In the below code we use Jquery inside the Content page so we write '#<%= Button1.ClientID %>' on the place of   '# Button1' because all the elements access on content page by ClientID.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="GridviewData.aspx.cs" Inherits="GridviewData" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
            $('#<%= Button1.ClientID %>').click(function () {
                alert('Hello Sudhir Singh');
            }

                );
        }
         
        );
    </script>
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
     
    </div>
</asp:Content>

NOw replace the

     $(document).ready(function(){
            $('#<%= Button1.ClientID %>').click(function () {
                alert('Hello Sudhir Singh');
            }

                );
        }
         
        );

Code with following code  this will not work properly because of we remove the $(documnet).ready() function.when you click on button you don't get alert message because

   
            $('#<%= Button1.ClientID %>').click(function () {
                alert('Hello Sudhir Singh');
            }

                );
        }
         
     


Friday, 25 August 2017

what are the Advantages of Jquery over Javascript ?

There are so many Advantages of Jquery over the JavaScript , some of them are described below.

1)Cross Browser Support
2)Jquery is Easy to use than JavaScript.
3)Jquery is able  to do more work with less code or we can say that in less line of codes we performs more work but in javascript we have to write more line of codes for same task.
4)Jquery is Extensible.
5)Jquery has Rich AJAX Support.
6)Jquery has large development community and many ready to use pluggins.
7)Jquery has excellent documentation and tutorials are available on Internet due to large community of developers.

For more understanding of above  points , I here want to explain some example for Cross Browser Support..

I have a line of code like

<script type="text/javascript">
         window.onload=   function ()
            {
document.getElementById("Button1").addEventListner('click',clickHandler,false)
};
function clickHandler()
{
alert("Hello Everyone");
}
</script>

The above code is works fine IE 11 but throwing a error on IE 6.....But in Jquery it is works fine with both the browsers.



What is Jquery ?

Jquery is Light weight JavaScript library that is used for simplify the programs in JavaScript or we can say that JQuery is used for "Write Less Do more " work.

According to JQuery.com , Jquery is fast,small,feature rich Java Script Library . JQuery makes things like HTML Document traversal and manipulation ,Event Handling,animation and AJAX much simpler with an easy to use API that works across a multitude of  browsers.

With a Combination of Versatility and Extensibility Jquery changed the ways that millions of people write the JavaScript.

You can Download the JQuery from JQuery.com and reference it in your application just like any other JavaScript files.
If you want to Support IE 6/7/8 then you have to use Jquery 1.X and if you don't want to support on it then use Jquery 2.X . Jquery 2.X is latest version of Jquery and it is small in size.  

How to Code for Password Strength Checker in javascript?

Here we use Java Script for checking the password strength ..
we are calculate the strength on the basis of five criteria that is defined below...

If  Password contains at least 8 characters then we add 20 number in score.
If  Password contains at least 1 lower case characters then we add 20 number in score.
If  Password contains at least 1 Uppercase characters then we add 20 number in score.
If  Password contains at least 1 number  then we add 20 number in score.
If  Password contains at least 1 special case characters then we add 20 number in score.


Here we use A textbox for Password and on the  onKeyup events of text box we call a javascript function to check the strength of password...

HTML and javascript code is given below.. Copy it and paste into the page and run ...

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <table>
             <tr>
            <td>
                <asp:Label ID="Label2" runat="server" Text="User Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtUserName"  runat="server"></asp:TextBox>
            </td></tr>
                  <tr>
            <td>
                <asp:Label ID="Label1" runat="server" Text="Password"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtPass" onKeyUp="CheckPasswordStrength()" TextMode="Password" runat="server"></asp:TextBox>
            </td>
         
            <td>
                <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
            </td>
        </tr>
        </table>
        <script type="text/javascript">
            function CheckPasswordStrength()
            {
                var PasswordTextBox = document.getElementById("txtPass");
                var password = PasswordTextBox.value;
                var Specialcharacter = "!@#$%^&*_~";
                var PasswordScore = 0;
                for(var i=0;i<=password.length;i++)
                {
                    if(Specialcharacter.indexOf(password.charAt(i))>-1)
                    {
                        PasswordScore += 20;
                    }
                }
                if(/[a-z]/.test(password))
                {
                    PasswordScore += 20;
                }

                if (/[A-Z]/.test(password)) {
                    PasswordScore += 20;
                }

                if (/[\d]/.test(password)) {
                    PasswordScore += 20;
                }
                if(password.length>=8)
                {
                    PasswordScore += 20;
                }
                var strength = "";
                var backgroundColor = " ";
                if(PasswordScore>=100)
                {
                    strength = "Strong";
                    backgroundColor = "Green";
                }
                else if (PasswordScore >= 80) {
                    strength = "Medium";
                    backgroundColor = "Gray";
                }
                else if (PasswordScore >= 60) {
                    strength = "Weak";
                    backgroundColor = "Maroon";
                }
                else  {
                    strength = "Very Weak";
                    backgroundColor = "Red";
                }
                document.getElementById("Label4").innerHTML = strength;
                PasswordTextBox.style.color = "White";
                PasswordTextBox.style.backgroundColor = backgroundColor;
            }
        </script>
      </div>
    </form>
</body>
</html>

How to add Content Page with Master Page in ASP.Net ?

Now we have to add the content page with master page SiteMaster.master that we have added in our previous post...

Right Click on Project Name ===> Add new Item ====> Web form
write the page name and select the  Select Master Page  and ADD


After clicking on add button Choose the Master page as shown in figure...


Write the code inside the content place holder 2.....


How to add Master Page in ASP.Net?

Master Page in asp.net is used for  Parent Form for more than one form with same design only content place is different.. It is used where we need same design for all the forms...

We can add Master Page by following Process...

Right Click on Project Name ===>>  Add New Item ====>  Select Master Page ===> Name the master page as you need==> Add

In the Below screen shot I have add a master page named it SiteMaster.master  (.master is the extension of master page.)



After add master page it will look like....Do not write any code in Content Place Holder....


You can code in master page like it....










Thursday, 17 August 2017

Data Navigation Techniques in ASP?

Data Navigations means send data from one web forms to another web forms . There are six data navigation techniques are present in the ASP.Net which are described below.
1)Cross Page PostBack
2)Context.handler
3)QueryString
4)Cookies
5)Session State
6)Application State

What is Query String ? Why we use Query Sting in ASP.Net?

Query String is Data Navigation technique which is used for Sending the data from one web form to another web forms.
Query String is Pair of Name/Value Collection and it is appended to the page URL.

For Example : if we have two web forms one is default1.aspx and another is default2.aspx.
User wants to send EmailID and UserName from Default1.aspx to default2.aspx then we have to append EmailId and UserName to URL like below code

Response.Redirect("Default2.aspx?UserName="+txtUsername.Text+"&EmailID="+txtEmail.text+);

Question Marks (?) indicated beginning of a Query String and it's value.
Ampersand (&) indicates another query sting variable.

In the Above example UserName is one variable in which we holds the values from txtUsername.text  and EmailID is the second variable which holds the value of EmailID.. so in the above code we use two query strings concatenate by & symbol.

There is some limitations of Query String data so that we can not send long data by query string.
Query strings are visible to the users so can not send the sensitive data by query string unless use ENCRYPTION of Url..
To read query string data we use Request object's Query string properties.


On the webform Default2.aspx load event we can read query string values like that

txtUserName=Request.QueryString["UserName"];
txtEmailId=Request.QueryString["EmailID"];

Saturday, 5 August 2017

How to write Query for creating a table and Inserting data into table in Sql Server ?


Here we are Creating the table Rolemaster_tbl , which will be used  on login page(in next post) so script for creating the table is given below.

create table Rolemaster_tbl
(RoleID int not null identity(1,1),
UserRole nvarchar(max) not null,
primary key(RoleID)
)

Create table is the Sql Command used for creating a table.
 Rolemaster_tbl is the name of table.



On the above query  Rolemaster_tbl is the name of table... RoleID is first column which is primary key and auto incremented by 1.
Once the table created than we have to add data into it , so here I  have written a script for inserting data into table.
Insert into Rolemaster_tbl(UserRole) values('Student');
Insert into Rolemaster_tbl(UserRole) values('Parent');
Insert into Rolemaster_tbl(UserRole) values('Teacher');
Insert into Rolemaster_tbl(UserRole) values('Admin');
Insert into Rolemaster_tbl(UserRole) values('Principal');
Insert into Rolemaster_tbl(UserRole) values('Transport');
Insert into Rolemaster_tbl(UserRole) values('Exam Control');

I only specify one column name Rolemaster_tbl(UserRole) rather than two columns Rolemaster_tbl(RoleID,UserRole) because RoleID is the Primary key and we do not need to specify primary key when we insert data into table.

Now run the Query  Select * from Rolemaster_tbl  on query window and show the result of table.
Output of Query is given below.

RoleID UserRole
1         Student
2         Parent
3         Teacher
4         Admin
5        Principal
6       Transport
7       Exam Control

Code on Submit button click for Submit data in ASP.Net?

In the previous posts , I clearly describe following things

Step1 : How to create database and table into database (Please read previous post)

Step2: After creating the table ,so we have to provide connetion string in web.config file, we need to provide connection string for establishments of  connection between ASP.Net application and SQL Server so i describe it in the post
How to set connection string in web.config file.(Please read previous post)

Step 3 : For Inserting data we require User Interface or web form , So in my previous post I describe How to design a web form.(Please read previous post)

Step 4 : Code for Entity Layer(Please read previous post)

Step 5: Code for DataLayer(Please read previous post)

Step6: Code on Button click (Learn in this post)

In This post we learn about how to call methods defined into the Datalayer and how to use properties defined in the EntityLayer.
 Complete code is given below copy and paste in your application and run it .

int genderid;
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
       
            studentregistration_BEL objStudent_BEL = new studentregistration_BEL();
            studentregistration_DAl objStudent_DAL = new studentregistration_DAl();
            objStudent_BEL.FirstName = txtFirstName.Text;
            objStudent_BEL.LastName = txtLastName.Text;
            objStudent_BEL.UserName = txtUserName.Text;
            objStudent_BEL.Password = txtPassword.Text;
            objStudent_BEL.Mobile = txtPhone.Text;
            objStudent_BEL.DOB = Convert.ToDateTime(txtDob.Text);
            objStudent_BEL.Email = txtEmailAddress.Text;

            if (rbFemale.Checked == true)
            {
                genderid = 1;
            }
            if (rbMale.Checked == true)
            {
                genderid = 2;
            }
            else
            {
                Response.Write("Please select Gender");
            }
  objStudent_BEL.GenderID=genderid  ;
            objStudent_DAL.RegisterStudent(objStudent_BEL);
            Response.Write("Student Registered");
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

How to code Data Access Layer in ASP.Net ?

Data Access Layer is the layer in which we define the Methods for CRUD Operations.
Here we are using a Student Registration for Insert data Submitted by Student from ASP Web form,
the step by step process is given below.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for studentregistration_DAl
/// </summary>
public class studentregistration_DAl
{
    public static string _connectionStr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    SqlConnection conn = new SqlConnection(_connectionStr);

    #region Save RegisterStudent
    public void RegisterStudent(studentregistration_BEL objStudentReg_BEL)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Insert_StudentRegistration";
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                    cmd.Parameters.Add("@GenderID", SqlDbType.Int).Value = objStudentReg_BEL.GenderID;
                    cmd.Parameters.Add("@firstname", SqlDbType.NVarChar).Value = objStudentReg_BEL.FirstName;
                    cmd.Parameters.Add("@lastname", SqlDbType.NVarChar).Value = objStudentReg_BEL.LastName;
                    cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = objStudentReg_BEL.UserName;
                    cmd.Parameters.Add("@DateOfBirth", SqlDbType.DateTime).Value = Convert.ToDateTime(objStudentReg_BEL.DOB).ToString("MM/dd/yyyy");
                    cmd.Parameters.Add("@MobileNumber", SqlDbType.NVarChar).Value = objStudentReg_BEL.Mobile;
                    cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = objStudentReg_BEL.Email;
                    cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = objStudentReg_BEL.Password;
                   cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (conn.State != ConnectionState.Closed)
            {
                conn.Close();
            }
        }
    }
    #endregion RegisterStudent
}


Firstly Create a folder into App_code folder of Profect and named it DATALAYER.
In DATALAYER ==> ADD NEW ITEM ==>Studentregistration_DAL  
In The Above Code STudentregistration_DAL is the name of CLass in which code is written and we
access connection from Web.config file and store it into the static variable _connectionStr and for accessing connetion string from web.config file we have to use Using System.Configuration name space at the top of the page.

   public static string _connectionStr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    SqlConnection conn = new SqlConnection(_connectionStr);

We use a method named  RegisterStudent for storing data and pass a object of  studentregistration_BEL  class
 public void RegisterStudent(studentregistration_BEL objStudentReg_BEL)

And then create command object and add parameters into it .....

Friday, 4 August 2017

How to write Stored Procedure for Insert Data into SQL Server by ASP.Net ?

Stored Procedure is block of SQL Statements or Queries which has some name and it is precompiled code and saved into the database.
Create procedure is used to create the procedure.
Stored procedure for inserting data is given below.

create procedure sp_Insert_StudentRegistration
(@firstname nvarchar(max),
@lastname nvarchar(max),
@MobileNumber nvarchar(50),
@GenderID int,
@DateOfBirth date,
@Email nvarchar(50),
@UserName nvarchar(50),
@Password nvarchar(50)
)
as
Begin
Begin Try
Begin Transaction
INSERT INTO StduentRegistration_tbl(FirstName,LastName,UserName,Password,EmailID,MobileNumber,DOB,GenderID)
Values(@firstname,@lastname,@UserName,@Password,@Email,@MobileNumber,@DateOfBirth,@GenderID)
commit transaction
End Try
Begin Catch
RollBack Transaction
select
ERROR_LINE() as errorline,
ERROR_MESSAGE() as errormessage
End Catch
End


On the above code sp_Insert_StudentRegistration is the stored procedure name.
we use create procedure command for creating a stored procedure.
@firstname nvarchar(max),
@lastname nvarchar(max),
@MobileNumber nvarchar(50),
@GenderID int,
@DateOfBirth date,
@Email nvarchar(50),
@UserName nvarchar(50),
@Password nvarchar(50)
are the parameters , in which we can  get the values from ASP.Net application.. Here @ is compulsory before the Parameter name and type should be exactly same with table datatypes.
name of parameters can be different from columns but datatypes should be same.

Begin   : Stored procedure is begin from here
End : Sp ends here

Begin Try
end Try  
Begin Catch
End catch  are the exception handling in Database.


How to write code in EntityLayer in ASP.Net?

For inserting data or create data records into the database , firstly we have to create database and tables , after that we have to design ASP.Net webforms for providing Interface.
Here we are using StudentRegistration table of Example database , in which
RegistrationID is the primaryKey
FirstName is type of  nvarchar(max)
Lastname is type of  nvarchar(max)
UserName is type of  nvarchar(max)
Password is type of  nvarchar(max)
Email is type of  nvarchar(max)
MobileNumber is type of  nvarchar(max)
GenderID is type of  int
DOB is type of Datetime..

So firstly we need to define properties into our application  so we use Entity Layer ....
So right click on Project and ADD a Folder called App_Code..

In App_Code add a folders called EntityLayer .
Right click on EntityLayer and add a class named studentregistration_BEL and paste the code below.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class studentregistration_BEL
{
    public studentregistration_BEL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
//Use can delete it.It is constructor mainly used for initializing the data members of any class.

    private int _registrationid;
    private int _genderid;
    private DateTime _dob;
    private string _firstname;
    private string _lastname;
    private string _username;
    private string _password;
    private string _email;
    private string _mobile;
    public int RegistrationID
    {
        get { return _registrationid; }
        set { _registrationid = value; }
    }
    public int GenderID
    {
        get { return _genderid; }
        set { _genderid = value; }
    }
    public DateTime DOB
    {
        get { return _dob; }
        set { _dob = value; }
    }
    public string FirstName
    {
        get { return _firstname; }
        set { _firstname = value;
        }
    }
    public string LastName
    {
        get { return _lastname; }
        set
        {
            _lastname = value;
        }
    }
    public string UserName
    {
        get { return _username; }
        set
        {
            _username = value;
        }
    }
    public string Password
    {
        get { return _password; }
        set
        {
            _password = value;
        }
    }
    public string Email
    {
        get { return _email; }
        set
        {
            _email = value;
        }
    }
    public string Mobile
    {
        get { return _mobile; }
        set
        {
            _mobile = value;
        }
    }


}




What is ADO.Net ?

ADO.Net : ADO Stands for Microsoft Activex Data Object is a set of Classes (frameworks) is used as a
intermediatory part between any Dot Net application and Different Datasources like Databases and XML
files.
ADO.Net esrablishes the connection between the datasource (oracle,sql server) and Dot net application. Firstly we have to make a connection with the Database and ASP application by connection string.
After establishes the connetion we need to create the connection object and open the connection.

Once connetion is open then we have to send commands by it , so we need sqlcommand object by which we can send and the queries or stored procedure parameters.

after that we can manuplate the data by datatable or we can read the data by sqlreader.

  <connectionStrings>
    <add name="DBCS" connectionString="Data Souce=PC ;Initial Catalog=Example; Integared Security=true"
          providerName="System.Data.SqlClient" />
  </connectionStrings>

 public static string _connectionStr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        SqlConnection conn = new SqlConnection(_connectionStr);


  using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "sp_Insert_Item_Master";
                    if(conn.State!=ConnectionState.Open)
                    {
                        conn.Open();

                        cmd.Parameters.Add("@ItemTypeID", SqlDbType.Int).Value = objInventoryAll.ItemTypeID;
                        cmd.Parameters.Add("@ItemAddedByUserID", SqlDbType.Int).Value = objInventoryAll.UserID;
          
                        cmd.ExecuteNonQuery();
                    }


On the Above code , SQLconnection class is used for establishes the connection with Database.
SQLCommand class is used for providing the Sql queries to the Sql connection for exexcution.

commandtype shows the type of sql commands.
commandtext shows the name of stored procedure.
con.open() opens the connection.
cmd.parameters.add() it adds the parameters to command object(cmd).


How to specify connection string in web configuration file(web.config) in ASP.Net ?

As you know all the configuration settings are present into the web configuration file .
In this file we are learning about how to add connection string into the web.config file.

open the web config file by default the code is written in it is like that

<?xml version="1.0"?>

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>

</configuration>

In the above code we have to add connection string for the connection to the database for save our data into the database.

So add following lines into it.

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=PC;Initial Catalog=Example;Integrated Security=true"
          providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Add the above marked lines into the web.config file.
DBCS ==> NAme of connection string
Data Source= => Name of server (PC is my computer name it can be a IP addreess like 154.21.145.12)
Initial Catalog ==> It is the database name
Integrated Security=true ====> Is is for windows authentication

for Sql Server Authentication repalce it with

User Id=xyz; password=******
The complete description is shown into the following diagrams.


How to design a web forms in ASP.Net?

This is the continue part of the previous post because we are learning about how to perform CRUD operations ASP.Net.
In previous part we create the database table and in this post we design a web form and write the code for save the data into SQL Server.

Open the visual studio 2015 and Click on File => New => website  as shown in fig below.


Select ASP.Net Empty Website and write the name for website like here we used name as ExampleASp and click ok.


Go to Tools => Solution explorer and wright click on it and Add new Item like the fig. below.
Select Web Forms and Click on Add button.


New web form frmRegistration.aspx  is open. Now design the forms by which we can save the records.

<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtFirstName" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label2" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
              <tr>
                <td>
                    <asp:Label ID="Label3" runat="server" Text="Last Name"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtLastName" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label4" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>

             <tr>
                <td>
                    <asp:Label ID="Label5" runat="server" Text="User Name"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtUserName" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label6" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
             <tr>
                <td>
                    <asp:Label ID="Label7" runat="server" Text="Password"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtPassword" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label8" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
             <tr>
                <td>
                    <asp:Label ID="Label13" runat="server" Text="Gender"></asp:Label>
                </td>
                 <td>
                     <asp:RadioButton ID="rbMale" Text="Male" GroupName="xyz" runat="server" />
                     <asp:RadioButton ID="rbFemale" Text="Female" GroupName="xyz" runat="server" />
                </td>
                <td>
                    <asp:Label ID="Label14" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label15" runat="server" Text="DOB"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtDob" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label16" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
               <tr>
                <td>
                    <asp:Label ID="Label9" runat="server" Text="Email Address"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtEmailAddress" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label10" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label11" runat="server" Text="Phone"></asp:Label>
                </td>
                 <td>
                     <asp:TextBox ID="txtPhone" Width="200px" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="Label12" runat="server" Text="*" style="color:red"></asp:Label>
                </td>
            </tr>

            <tr>
                <td>
                    <asp:Button ID="btnSave" runat="server" Text="Register" />
                    <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body> 

Note :- In radio button Define the group name whatever you need but group name should be same for both radio buttons ... Here we use xyz for group name...

The design view is given Below.


You can Apply more CSS on it for look and feel.


How to create table in SQL server?

How to Create table in SQL Server ?
After long time i come back on Blogger due to some busy schedule , i was not able to write blogs on ASP.Net  since  last 5 months. Now here on demand of students ,trainee and some beginner level developers , they sent me few emails and request to write blogs on CRUD  operations in ASP.Net with two tier architecture and three tier architecture , this is my first post after a long Interval.

Firstly i would like to define what is CRUD Operations?
CRUD stands for Create , Read , Update and Delete operations inASP.net , so we need a database for storing the records . so our first step is to create a database , and a table for storing the records in it.

We are using SQL Server 2008 R2 as database and visual studio 2015 for IDE .

Step 1 :- Create a database and table into SQL Server.
Step 2 :- Design a ASP.Net  Web forms to SAVE Data.

Open the SQL server Management Studio like the process given below.

After Clicking on the Icon presented on the above screen . SQL Server Management tools will open shown in below Image.



 On the Above Image , Choose server Type as DataBase Engine
Server Name : it is the name of database server where our data will store , on the above pic PC is the name of Database server because we are using Local Host or local system so our Computer name will be the server name , you can also used the
(local) or . (dot) for Server name for local host.
Authentication means which type of authentication you are using like SQL Server Authentication
or windows authentication.
we are using windows authentication for local , so we don't need user name and password to write here.
If you are using a Database server with IP address then following will be the process for creating the database.
In SQL Server Authentication mode we need Login UserName and Password as shown in below figure
Click on Connect Button and Sql Server will open as shown in below fig.
Write Click on database and select add new DataBAse.


Example is the Database Name and click Ok......


Write click on tables and select New table.


Write the column names and choose the datatypes for columns and make the RegistrationID as a primary key for right click and set as primary key.




Save the table as StudentRegistration_tbl.
we can also create the table with query given below.

CREATE TABLE StduentRegistration_tbl
(
RegistrationID int IDENTITY(1,1) NOT NULL,
FirstName  nvarchar(max) NOT NULL,
LastName nvarchar(max) NOT NULL,
UserName nvarchar(max) NOT NULL,
Password nvarchar(max) NOT NULL,
EmailID nvarchar(max) NULL,
MobileNumber nvarchar(50) NOT NULL,
DOB datetime NULL,
GenderID  int  NOT NULL,
 CONSTRAINT [PK_StduentRegistration_tbl] PRIMARY KEY CLUSTERED 
(
[RegistrationID] ASC
)
) ON [PRIMARY]









Creating First WEB API Project from scratch ?

  For creating Web API project open your Visual Studio Editor and Create New Project as shown in below figure. Now you have to select  ASP.N...