Insert, Update, Delete Data in ASP.NET (ADO.NET)

·

1 min read

Insert, Update, Delete Data in ASP.NET (ADO.NET)
using System;
using System.Data;
using System.Data.SqlClient;
public partial class Insert : System.Web.UI.Page
{
    static string cs = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
    SqlConnection con = new SqlConnection(cs);
    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        if (con.State == ConnectionState.Open)
        {
            lblAction.Text = "Database Connected";
        }
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        string query = "insert into Students(name, city, country) values('" + txtName.Text + "', '" + txtCity.Text + "', '" + txtCountry.Text + "')";

        SqlCommand cmd = new SqlCommand(query, con);
        int check = cmd.ExecuteNonQuery();
        if (check > 0)
        {
            lblAction.Text = "Data Inserted";
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string query = "delete from Students where name = ('" + txtName.Text + "')";
        SqlCommand cmd = new SqlCommand(query, con);
        int check = cmd.ExecuteNonQuery();
        if (check > 0)
        {
            lblAction.Text = "Data Deleted";
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string query = "update Students set name = '" + txtName.Text + "', city ='" + txtCity.Text + "', country ='" + txtCountry.Text + "' WHERE name ='" + txtName.Text + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        int check = cmd.ExecuteNonQuery();
        if (check > 0)
        {
            lblAction.Text = "Data Updated";
        }
    }
}