15 February 2014

How to Add SQL Database (.mdf) in ASP.NET Website

Hai ! Now Give information about how to Add .mdf Database in ASP.NET Application.

There are some steps to Add SQL Database (.mdf) in ASP.NET Website. Which are given below:
Step1:-
First open your visual studio 2010-> go File-> click New Website->Select ASP.NET Empty website->click OK.
Go Solution Explorer->Add New web form(Default.aspx)-->Drag and drop some controls as shown below :-
see it:-

Step2:- Now open Solution Explorer-> Right mouse click on website(Application) which is as  shown below:-
See it:-

Now Select SQL Server Database->click Add button ,which is shown below:-
see it:-

Step3:-  Now Double click on Database.mdf File in Solution Explorer->Now  Right click on Tables  Click Add New Table->Now Write required column Name-> Click save  button ->Write the table NAME-> Click OK. which is  as shown below :-
see it:-


Step4:-  Now Double click on Submit Button -> Write the following code for Database connectivity which are given below:-

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=SHIVACHARAN-PC;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");

    con.Open();
    String str = "INSERT INTO login (username,password) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "')";
    SqlCommand cmd = new SqlCommand(str, con);
    int OBJ = Convert.ToInt32(cmd.ExecuteNonQuery());
    if (OBJ > 0)
    {
        Label3.Text = "Data is successfully inserted in database";
    }
    else
    {
        Label3.Text = "Data is not inserted in database";
    }
    con.Close();

    }
}
see it:-
Step5:-  Run the Application(Press F5).Which are shown below:
Output:-
Step6:- Now you can see the inserted data in Database.
see it:-


No comments:

Post a Comment