mi1an
mi1an's Blog

mi1an's Blog

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

Insert, Update, Delete Data in ASP.NET (ADO.NET)
mi1an's photo
mi1an

Published on Nov 4, 2021

1 min read

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";
        }
    }
}
 
Share this