Connecting to MS SQL Database in ASP .NET
Creating a Connection
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open } }
|
How to know about your SqlConnection
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open Label1.Text = newConnection.State.ToString(); Label2.Text = newConnection.ServerVersion.ToString(); newConnection.Close();// Connection Close } }
|
Read Data from Database using SqlDataReader
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open //Command Query SqlCommand cmd = new SqlCommand("Select * from emp_tbl", newConnection); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { GridView1.DataSource = dr; //Using GridView to Show the data. GridView1.DataBind(); } newConnection.Close();// Connection Close } }
|
Using SqlDataAdapter Fill the GridView
protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl",newConnection); DataSet ds = new DataSet(); ad.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); } |
0 comments:
Post a Comment