How To Make a Connection Database SQL Server Using C# Based Web

6:54 AM 0 Comments A+ a-

We make a connection into database before we can insert, update, or deleting a query in table. After all, this is the first step to make any change in our database. Before we make a connection code, you must already have the database and its table (we will teach you how to make it later in different post). You need to a web application, if you want to make insert or update code later.

So, if you already have it all, go into code behind and check if your .aspx.cs file has this code on its top:

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

Sure, we need data sql client to make a connection into database. If you already has this all code, add connection variables in your public class, like this:

private string connection = WebConfigurationManager.ConnectionStrings["Database"].ConnectionString;

Change the word "Database", as your database name in your web.configuration.
Then create an event for one of your button, so you can insert a query into your database.

protected void btn_Click(object sender, EventArgs e)
{
}

Change the word btn as your button ID. Now, insert all of codes below in the parenthesis of btn_Click
First, you can INSERT/ UPDATE/ DELETE for SQL variables, here we give the example of INSERT code:

string SQL = "INSERT INTO t_mahasiswa (column1,column2) VALUES ('" + txtBox1.Text + "','" + txtBox2.Text + "')";

Change the word column1 and column2 as your table column name, you can the column too as you wish.
Change the word txtBox1 and txtBox2 as your textBox name that you want its value to be inserted into database.

Then add connection and insert code to make a connection into database

SqlConnection conn = new SqlConnection(connection);
SqlCommand comm = new SqlCommand(SQL, conn);

To make all of codes above work, you need to add a trigger,

try
{
conn.Open();
comm.ExecuteNonQuery();

txtBox1.Text = "";
txtBox2.Text = "";
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}

Don't forget to change the word txtBox1 and txtBox2 as your txtBox name.