Published on: 03 Aug, 2013

How to Connect to Microsoft SQL Server using ASP.Net C#?

Tumblr Digg Google Plus

This tutorial will show you how you can connect to MS SQL server using ASP.Net C#.

First of all, you will need to import the SqlClient namespace into your project or site page.

//required sql namespace
using System.Data.SqlClient;

The following quick function will connect to the MS SQL server. Basically it defines the SqlConnection object and attaches a connection string value into the object. The .Open() method will try to connect to the server and .Close() method basically will close the database connection.

//private function for testing connection
private void ConnectToSQL() {
    string connectionString = @"Data Source=\SQLEXPRESS;Initial Catalog=DBNAME_HERE;User ID=USERNAME_HERE;Password=PASSWORD_HERE";
    using (SqlConnection objSqlConnection = new SqlConnection(connectionString)) {
        try {
            Response.Write("Connection is successfull");
        } catch (Exception ex) {
            Response.Write("Error : " + ex.Message.ToString());

To test it, you can call the function in the Page_Load method just to see what will happen. Remember to set the connectionstring correctly according to your setting.

//Sample on how to use it
protected void Page_Load(object sender, EventArgs e) {
    if (!Page.IsPostBack) {


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.