Wednesday 24 April 2013

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


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



There are some steps to Add SQL Database (.mdf) in ASP.NET Website. Please follow below steps one by one.
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) which is given below:-
see it:- 



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


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



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





Step4:-  Now Double click on Submit Button -> Write the following code for connectivity which is given below:-
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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=RAMASHANKER-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).
OUTPUT:-



Step6:- Now you can see the inserted data in Database.
see it:-


I hope this is helpful for you.

Click the below link to download the whole Application.
               DOWNLOAD

No comments:

Post a Comment