C# Database Connection

Introduction

Accessing Data from a database is one of the important aspects of any programming language.

It can work with different types of databases. It can work with the most common databases such as Oracle and Microsoft SQL Server. Most of the C# programs work with Microsoft SQL Server. It also can work with new forms of databases such as MongoDB.

We will see a simple web application to work with databases. We will have a simple button called “Connect” which will be used to connect to the database.

So let’s follow the below steps to achieve this.

Step 1

The first step is the creation of a new project in Visual Studio.  After launching Visual Studio, you need to choose the menu option New->Project.

C# Database Connection

Step 2

The next step is to choose the project type as a Web Application. Here, we also need to mention the name and location of our project.

C# Database Connection

Step 3

Choose Empty Project and click on OK.

C# Database Connection

Step 4

After Creating an empty web application add webform to the application by following menu.

Rightclick on Project->Add->New Item

C# Database Connection

Step 5

Select WebForm give name for it and click on Add.

C# Database Connection

Step 6

We are created empty application. We have to set default page for created application. Right click on the webform and set as start page.

C# Database Connection

Step 7

Add the following code in webform.aspx page

<head runat="server">
  <title></title>
  <style type="text/css">
    .lblcolor {
      color: green;
    }
  </style>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <h1>DataBase Connection</h1>
      <div>
        <div>
          <asp:Button runat="server" Text="Connect" OnClick="btn_connect_Click" ID="btn_connect" />
        </div>
        <div>
          <asp:Label ID="lblmsg" CssClass="lblcolor" runat="server" Text=""></asp:Label>
        </div>
      </div>
    </div>
  </form>
 </body>
</html>

Step 8

Add the following code in the WebForm.aspx.cs page

protected void btn_connect_Click(object sender, EventArgs e) {
    string connetionString;
    SqlConnection cnn;
    connetionString = @ "Data Source=WIN-787926;Initial Catalog=testdb;User ID=sa;Password=sa@l23";
    cnn = new SqlConnection(connetionString);
    cnn.Open();
    lblmsg.Text = "Successfully Connected to database !";
    cnn.Close();
}

Step 9

Click on F5 to execute the program.

C# Database Connection

Step 10

Click on Connect button.

C# Database Connection

Database connected successfully.