Friday, 14 February 2014

Insert Data into database


Inserting data into a database is a simple process in ASP.NET.As compared to PhP and JAVA in ASP.NET there is no need to write all connection stuffs, instead only just map the connection string to application and here's the connection created,
Now today i am going to show you a demo of how to Insert Data in database using ASP.NET & SQL Server.

Consider you have a Table named Employee in database: And the form you designed is some what like this :
Employee Name:
Employee Contact:

Html Source :
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;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);

     protected void Page_Load(object sender, EventArgs e)
    {
       
    }
 protected void insrtbtn_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select EmployeeName from Employee where EmployeeName='"+txtName.Text+"'",con);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            Response.Write("Data already exist");

        }

        else
        {
            con.Close();
            con.Open();
            SqlCommand insrt = new SqlCommand("insert into Employee(EmployeeName,EmployeeContact) values('"+txtName.Text+"','"+txtcontact.Text+"')",con);
            insrt.ExecuteNonQuery();
            con.Close();
            Response.Write("Data inserted");
           
        
        }
    }
      
Hope you like this inserting data for any query regarding ASP.NET just contact me.

No comments:

Post a Comment

How To Pass An Array As A Parameter While Calling an ASP.NET Web API C#

Please visit my C# Corner Blog for this, where I have provided better efforts to make this concept more understandable - www.c-sharpcorner....