0% found this document useful (0 votes)
1 views

Data Connectivity Using ASP.net

Uploaded by

ragini4651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Data Connectivity Using ASP.net

Uploaded by

ragini4651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

CREATE TABLE Employees (

Id INT PRIMARY KEY IDENTITY,

Name NVARCHAR(50),

Department NVARCHAR(50)

<connectionStrings>

<add name="MyDBConnection" connectionString="Data Source=.;Initial


Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />

</connectionStrings>

using System;

using System.Data;

using System.Data.SqlClient;

namespace DataAccessExample

public class EmployeeData


{

private string connectionString =


System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].Connection
String;

// Method to Fetch Data

public DataTable GetEmployees()

DataTable dt = new DataTable();

using (SqlConnection con = new SqlConnection(connectionString))

string query = "SELECT * FROM Employees";

using (SqlCommand cmd = new SqlCommand(query, con))

con.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dt);

return dt;

// Method to Insert Data

public void InsertEmployee(string name, string department)

using (SqlConnection con = new SqlConnection(connectionString))

string query = "INSERT INTO Employees (Name, Department) VALUES (@Name,


@Department)";

using (SqlCommand cmd = new SqlCommand(query, con))


{

cmd.Parameters.AddWithValue("@Name", name);

cmd.Parameters.AddWithValue("@Department", department);

con.Open();

cmd.ExecuteNonQuery();

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

EmployeeData data = new EmployeeData();

GridView1.DataSource = data.GetEmployees();

GridView1.DataBind();

protected void BtnAdd_Click(object sender, EventArgs e)

EmployeeData data = new EmployeeData();

data.InsertEmployee(txtName.Text, txtDepartment.Text);

Response.Redirect(Request.RawUrl); // Refresh Page

You might also like