Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

C# Database Lab Manual PDF

Download

Uploaded by

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

C# Database Lab Manual PDF

Download

Uploaded by

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

Session: Working With Database Connectivity

Acivity: Connecting to database by using visual studio tools


Design

Running

pg. 1
Activity: Adding, Saving, Deleting and Navigating Records
During design:

Running
 Adding Records

pg. 2
 Saving Records

pg. 3
 Deleting Records

pg. 4
 Navigating Records
 MoveNext
 MoveLast
 MoveFirst
 MovePrevious

pg. 5
Activity: Querying Records and displaying on list box
During Design

Coding
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QueryingOnGUI{
public partial class Form1 : Form{
public Form1(){
InitializeComponent(); }
SqlConnection con = new SqlConnection("Data Source=DIRES;Initial Catalog=University;"+

pg. 6
"Integrated Security=True");
private void button1_Click(object sender, EventArgs e){
try {
con.Open();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText = "SELECT * From Student";
command.ExecuteNonQuery();//Execute the command using the ExecuteNonQuery Method
SqlDataReader read = command.ExecuteReader();
while (read.Read()) {
lstStudents.Items.Add(read["Sud_Id"] + "\t" + read["First_Name"] + "\t" + read["Last_Name"] +
"\t" +read["Gender"] + "\t" + read["Gpa"]);
lstStudents.Items.Add("");}
read.Close(); }
catch(SqlException){
MessageBox.Show("There is error", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error); }
try {
con.Close();}
catch (SqlException) {
MessageBox.Show("Unable to close", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error); }}}}
Sample output

pg. 7
Activity: Querying From Db
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QueryingandDisOnlistBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnQuery_Click(object sender, EventArgs e)
{
String Connection = "Data Source=DIRES;Initial Catalog=Registrar;Integrated
Security=True";
SqlConnection con= new SqlConnection(Connection);
try {
con.Open();
SqlCommand com = new SqlCommand("Select* From StudData");
com.Connection = con;
com.ExecuteNonQuery();
SqlDataReader read = com.ExecuteReader();
while (read.Read()) {

pg. 8
lstStudents.Items.Add(read["Student_Name"]+"\t"+read["ID_No"]+"\t"+read["Mid_Result"]+"\t"
+read["Final_Result"]+"\t"+read["Total_Result"]+"\t"+read["Grade"]);
lstStudents.Items.Add("");
}
read.Close();
}
catch(SqlException) {
MessageBox.Show("Error in connection", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
try {
con.Close();
}
catch(SqlException){
MessageBox.Show("Error in closing", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
Sample Output

pg. 9
Activity:Using Dataset,Adapter
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace UsingDataSet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
myConnection.ConnectionString = "Data Source=DIRES; Initial
Catalog=Registrar;Integrated Security=True";
try
{
myCommand.Connection = myConnection;
myCommand.CommandText = "Select*From StudData";
adapter.SelectCommand = myCommand;

pg. 10
adapter.Fill(ds, "StudData");
foreach (DataRow StudData in ds.Tables["StudData"].Rows)
{
lstStudents.Items.Add(StudData["Student_Name"] + "\t" + StudData["ID_No"] + "\t" +
StudData["Mid_Result"] + "\t" + StudData["Final_Result"] + "\t" + StudData["Total_Result"] +
"\t" + StudData["Grade"]);
lstStudents.Items.Add("");
dataGridView1.DataSource = ds.Tables["StudData"];
}
}
catch (SqlException) {
MessageBox.Show("Error");
}
}
}
}
Sample output

pg. 11
Activity: Insert, Delete, Update Records
Design: Form

Running

pg. 12
pg. 13
pg. 14
Coding:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDelete
{
public partial class Form1 : Form
{
SqlConnection myCon = new SqlConnection(@"Data Source= DIRES; Initial Catalog =
EmployeeDB; Integrated Security=True;");
SqlCommand myCommand = new SqlCommand();
SqlDataReader dr;

pg. 15
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myCommand.Connection = myCon;
loadList();
}
private void loadList() {
lstEmp_Id.Items.Clear();
lstSex.Items.Clear();
lstAge.Items.Clear();
lstRank.Items.Clear();
myCon.Open();
myCommand.CommandText = "Select*From Employee";
dr = myCommand.ExecuteReader();
if (dr.HasRows) {
while (dr.Read()) {

lstEmp_Id.Items.Add(dr[0].ToString());
lstEmp_Id.Items.Add("");
lstSex.Items.Add(dr[1].ToString());
lstSex.Items.Add("");
lstAge.Items.Add(dr[2].ToString());
lstAge.Items.Add("");
lstRank.Items.Add(dr[3].ToString());
lstRank.Items.Add("");
}
}
myCon.Close();

pg. 16
}
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtEmp_id.Text !="" & txtAge.Text != "" & txtSex.Text != "" & txtRank.Text!="") {
myCon.Open();
myCommand.CommandText = "Insert into Employee(Emp_Id,Sex,Age,Rank) values('"
+ txtEmp_id.Text + "','" + txtSex.Text + "','" + txtAge.Text + "','" + txtRank.Text + "')";
myCommand.ExecuteNonQuery();
myCon.Close();
MessageBox.Show("Record Saved", "Save", MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtEmp_id.Text = "";
txtSex.Text = "";
txtAge.Text = "";
txtRank.Text = "";
loadList();
}
}
private void lstRank_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1) {
lstEmp_Id.SelectedIndex = l.SelectedIndex;
lstSex.SelectedIndex = l.SelectedIndex;
lstAge.SelectedIndex = l.SelectedIndex;
lstRank.SelectedIndex = l.SelectedIndex;
txtEmp_id.Text = lstEmp_Id.SelectedItem.ToString();
txtSex.Text = lstSex.SelectedItem.ToString();
txtAge.Text = lstAge.SelectedItem.ToString();
txtRank.Text = lstRank.SelectedItem.ToString();
}

pg. 17
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtEmp_id.Text!= "" & txtSex.Text!= "" & txtAge.Text!= "" & txtRank.Text!= "") {
myCon.Open();
myCommand.CommandText = "Delete from Employee where Emp_Id='" +
txtEmp_id.Text + "' and Sex='" + txtSex.Text + "'and Age='" + txtAge.Text + "' and Rank='" +
txtRank.Text + "'";
myCommand.ExecuteNonQuery();
myCon.Close();
MessageBox.Show("Record Deleted", "Delete", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
loadList();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEmp_id.Text != "" & txtSex.Text != "" & txtAge.Text != "" & txtRank.Text != "")
{
myCon.Open();
myCommand.CommandText = "Update Employee set Emp_Id='" + txtEmp_id.Text +
"',Sex='" + txtSex.Text + "',Age='" + txtAge.Text + "',Rank='" + txtRank.Text + "' where
Emp_Id='" +lstEmp_Id.SelectedItem.ToString()+ "'and Sex='" +lstSex.SelectedItem.ToString()+
"'and Age='" +lstAge.SelectedItem.ToString() + "'and Rank='"
+lstRank.SelectedItem.ToString()+ "'";
myCommand.ExecuteNonQuery();
myCon.Close();
MessageBox.Show("Record Updated", "Update", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtEmp_id.Text = "";
txtSex.Text="";

pg. 18
txtAge.Text = "";
txtRank.Text="";
loadList();
}
}
}
}

Activity: Connecting to database and manipulating records


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace DbDemo2{
class Program{
static void Main(string[] args){
SqlConnection myConnection = new SqlConnection("Data Source=DIRES;Initial
Catalog=Registrar; Integrated Security=True");
String name, id,grade="";
double mid, final, total;
Console.WriteLine("Enter student's name");
name = Console.ReadLine();
Console.WriteLine("Enter "+name+"'s id");
id = Console.ReadLine();
Console.WriteLine("Enter " + name + "'s mid result");
mid = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter " + name + "'s final result");
final = Convert.ToDouble(Console.ReadLine());
total = mid + final;

pg. 19
if (total > 80)
grade = "A+";
else if (total > 75)
grade = "A";
else if (total > 70)
grade = "B";
else if (total >= 60 && total <= 70)
grade = "C";
try{
myConnection.Open();}
catch (Exception e) {
Console.WriteLine(e.ToString());}
try{
SqlCommand myCommand = new SqlCommand("Insert into
StudData(Student_Name,ID_No,Mid_Result,Final_Result,Total_Result,Grade)" +
"Values('"+name+"','"+id+"',"+mid+", "+final+","+total+",'"+grade+"')", myConnection);
myCommand.ExecuteNonQuery();
myCommand.CommandText = "SELECT*From StudData";
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
Console.WriteLine("Student Name\t"+myReader["Student_Name"]);
Console.WriteLine();
Console.WriteLine("ID No\t\t" + myReader["ID_No"]);
Console.WriteLine();
Console.WriteLine("Mid Result\t" + myReader["Mid_Result"]);
Console.WriteLine();
Console.WriteLine("Final Result\t" + myReader["Final_Result"]);
Console.WriteLine();
Console.WriteLine("Total Result\t" + myReader["Total_Result"]);
Console.WriteLine();
Console.WriteLine("Grade\t\t" + myReader["Grade"]);}}

pg. 20
catch (Exception e) {
Console.WriteLine(e.ToString());}
try{
myConnection.Close();}
catch (Exception e) {
Console.WriteLine(e.ToString());}
Console.ReadKey();}}}
Sample input and output

Activity: Inserting Records

pg. 21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace CreatingConnection
{
class Program
{
static void Main(string[] args)
{
//Creating connection using connection class
SqlConnection myConnection = new SqlConnection("Data Source=DIRES;"+
"Initial Catalog=University;Integrated Security=True");
String sid, fname, lname, gender;
double gpa;
Console.WriteLine("Enter Id no of student");
sid = Console.ReadLine();
Console.WriteLine("Enter firstname of student");
fname = Console.ReadLine();
Console.WriteLine("Enter lastname of student");
lname= Console.ReadLine();
Console.WriteLine("Enter gender of student");
gender = Console.ReadLine();
Console.WriteLine("Enter gpa of student");
gpa = Convert.ToDouble(Console.ReadLine());
try
{
myConnection.Open();

pg. 22
SqlCommand myCommand = new SqlCommand();//Create a command object using command
class
myCommand.Connection = myConnection;//initializing the connection property
myCommand.CommandText = "Insert into
Student(Sud_id,First_Name,Last_Name,Gender,Gpa)"+
"Values('" + sid + "','" + fname + "','" + lname + "','" + gender + "',"+gpa+")";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Select*From Student";
myCommand.ExecuteNonQuery();//Execute the command through ExecuteNonQuery method
SqlDataReader myReader = myCommand.ExecuteReader();//Execute using the ExecuteReader
method
Console.WriteLine("Stud_Id\t" + "First_Name\t" + "Last_Name\t" + "Gender\t" + "Gpa");
while (myReader.Read()) {
Console.WriteLine(""+myReader["Sud_Id"] + myReader["First_Name"] +
myReader["Last_Name"] + myReader["Gender"] + myReader["Gpa"]);
Console.WriteLine();
}
myReader.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (SqlException e) {
Console.WriteLine(e.ToString());
}
Console.ReadKey();} }}

pg. 23
Sample input and output

Activity: Inserting Records


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertingAndSaving
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

pg. 24
String name, id;
double mid, final, total;
SqlConnection mycon = new SqlConnection("Data Source=DIRES;Initial
Catalog=Registrar;Integrated Security=True");
SqlCommand mycommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
private void btnAddNew_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtId.Text = "";
txtMid.Text = "";
txtFinal.Text="";
txtTotal.Text = "";
txtGrade.Text = "";
}
private void btnSave_Click(object sender, EventArgs e)
{

try
{
mycon.Open();

name = txtName.Text;
id = txtId.Text;
mid = Convert.ToDouble(txtMid.Text);
final = Convert.ToDouble(txtFinal.Text);
total = mid + final;
txtTotal.Text = String.Concat(total);
if (Convert.ToDouble(txtTotal.Text) >= 90)
txtGrade.Text = "A+";
else if (Convert.ToDouble(txtTotal.Text) >= 85)
txtGrade.Text = "A";
else if (Convert.ToDouble(txtTotal.Text) >= 80)
txtGrade.Text = "A-";
else if (Convert.ToDouble(txtTotal.Text) >= 75)
txtGrade.Text = "B+";
else if (Convert.ToDouble(txtTotal.Text) >= 70)
txtGrade.Text = "B";
else if (Convert.ToDouble(txtTotal.Text) >= 65)
txtGrade.Text = "B-";
else if (Convert.ToDouble(txtTotal.Text) >= 60)
txtGrade.Text = "C+";
else if (Convert.ToDouble(txtTotal.Text) >= 50)
txtGrade.Text = "C";
else if (Convert.ToDouble(txtTotal.Text) >= 45)

pg. 25
txtGrade.Text = "C-";
else if (Convert.ToDouble(txtTotal.Text) >= 40)
txtGrade.Text = "D";
else if (Convert.ToDouble(txtTotal.Text) >= 30)
txtGrade.Text = "Fx";
else if (Convert.ToDouble(txtTotal.Text) < 30)
txtGrade.Text = "F";
mycommand.CommandText = "Insert into
StudData(Student_Name,ID_No,Mid_Result,Final_Result,Total_Result,Grade) Values('" + name
+ " ',' " + id + "'," + mid + "," + final + "," + total + ",'" + txtGrade.Text + "')";
mycommand.Connection = mycon;
adapter.InsertCommand = mycommand;
mycommand.ExecuteNonQuery();
MessageBox.Show("Data Saved", "Successfull", MessageBoxButtons.OK,
MessageBoxIcon.Information);
mycommand.CommandText = "Select*From StudData";
adapter.SelectCommand = mycommand;
adapter.Fill(ds, "StudData");
dataGridView1.DataSource = ds.Tables["StudData"];
}
catch (SqlException) {
MessageBox.Show("Unable to Connect");
}
mycon.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
mycon.Open();
mycommand.CommandText = "SELECT*From StudData";
mycommand.Connection = mycon;
adapter.SelectCommand = mycommand;
mycommand.ExecuteNonQuery();
adapter.Fill(ds, "StudData");
dataGridView1.DataSource = ds.Tables["StudData"];
}
catch (SqlException) {
MessageBox.Show("Unable to Connect");

}
}
}

pg. 26
Sample output

Activity: Inserting a record using addWithValue method


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;

pg. 27
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AnotherWayOfInsertion
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DIRES;Initial
Catalog=Registrar;Integrated Security=True");
SqlCommand command=new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
private void btnAdd_Click(object sender, EventArgs e)
{
command.CommandText="Insert into
Instructors(Name,Inst_Id,Age,Qualification,Field_Of_Specialization)"+
"Values(@Name,@Inst_Id,@Age,@Qualification,@Field_Of_Specialization)";
command.Connection=con;
command.Parameters.AddWithValue("@Name",richTextBox1.Text);
command.Parameters.AddWithValue("@Inst_Id",richTextBox2.Text);
command.Parameters.AddWithValue("@Age",richTextBox3.Text);
command.Parameters.AddWithValue("@Qualification",richTextBox4.Text);
command.Parameters.AddWithValue("@Field_Of_Specialization",richTextBox5.Text);
try
{
con.Open();
int result = command.ExecuteNonQuery();

pg. 28
if (result > 0)
MessageBox.Show("Record Added", "Sucess", MessageBoxButtons.OK,
MessageBoxIcon.Information);
else
MessageBox.Show("Failed to add a record", "Fail", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (SqlException)
{
MessageBox.Show("Unable to open");
}
finally {
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
command.CommandText = "Select*From Instructors";
adapter.SelectCommand = command;
adapter.Fill(ds, "Instructors");
dataGridView1.DataSource = ds.Tables["Instructors"];
}
catch (SqlException)
{
MessageBox.Show("Unable to open");
}
finally {
con.Close();}}}}

pg. 29
Sample output

pg. 30
pg. 31
Activity: Saving, Updating, Deleting and viewing records from Database
Design:

Running
Saving:

pg. 32
Viewing Records:

Updating Records:

pg. 33
pg. 34
Deleting Records:

pg. 35
Coding:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

pg. 36
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataEntry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DIRES;Initial
Catalog=DATAENTRY;Integrated Security=True;Pooling=False");
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Insert into
REGISTER(ID,NAME,GENDER,AGE,SALARY,TAX) values('" +txtID.Text + "','" +
txtName.Text + "','" +cmbGender.Text+ "','" + txtAge.Text + "','" + txtSalary.Text + "','" +
txtTax.Text + "')",con);
if (MessageBox.Show("Are u sure to save the entered record?", "Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Saved Successfully", "Save", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
con.Close();
}

pg. 37
private void btnView_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From REGISTER", con);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Update REGISTER set NAME='" +
txtName.Text + "',GENDER='" + cmbGender.Text + "',AGE='" + txtAge.Text + "',SALARY='" +
txtSalary.Text + "',TAX='" + txtTax.Text + "' where ID='"+txtID.Text+"'", con);
if (MessageBox.Show("Are u sure to update the record?", "Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Updated Sucessfully", "Update", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
con.Close();
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
cmbGender.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
txtAge.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
txtSalary.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();

pg. 38
txtTax.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
}
private void btnDelete_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Delete From REGISTER where ID='" +
txtID.Text + "'", con);
if (MessageBox.Show("Are u sure to delete selected record?", "Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Deleted Sucessfully", "Delete", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
con.Close();
}
}
}

pg. 39
Activity: Insert, Update, Delete and View records
Design:

Running:
Saving:

pg. 40
Viewing records

Updating Records

pg. 41
pg. 42
Deleting Records

pg. 43
Coding
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StudentProfile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection myCon = new SqlConnection("Data Source=DIRES;Initial
Catalog=Alumini;Integrated Security=True;Pooling=False");
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
private void btnSave_Click(object sender, EventArgs e)
{
myCommand.CommandText = "Insert into
Student(Stud_Id,First_Name,Last_Name,Gender,Department,CGPA)
values(@Stud_Id,@First_Name,@Last_Name,@Gender,@Department,@CGPA)";
myCommand.Connection = myCon;
myCommand.Parameters.AddWithValue("@Stud_Id",txtStudid.Text);
myCommand.Parameters.AddWithValue("@First_Name",txtFname.Text);
myCommand.Parameters.AddWithValue("@Last_Name",txtLname.Text);

pg. 44
myCommand.Parameters.AddWithValue("@Gender",txtGender.Text);
myCommand.Parameters.AddWithValue("@Department",txtDepartment.Text);
myCommand.Parameters.AddWithValue("@CGPA",txtCgpa.Text);
try {
myCon.Open();
if (MessageBox.Show("Are u sure to save the record entered?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
if (myCommand.ExecuteNonQuery() > 0) {
MessageBox.Show("Record Saved", "Save");
}
}
myCon.Close();
}
catch(SqlException ex){
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
txtStudid.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtFname.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
txtLname.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
txtGender.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
txtDepartment.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
txtCgpa.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
}
private void btnView_Click(object sender, EventArgs e){
myCommand.CommandText = "Select *From Student";
myCommand.Connection = myCon;
adapter.SelectCommand = myCommand;
DataSet ds = new DataSet();

pg. 45
adapter.Fill(ds,"Student");
dataGridView1.DataSource = ds.Tables["Student"];
}
private void btnUpdate_Click(object sender, EventArgs e){
myCommand.CommandText = "Update Student set
First_Name=@First_Name,Last_Name=@Last_Name,Gender=@Gender,Department=@Depart
ment,CGPA=@CGPA where Stud_Id=@Stud_Id";
myCommand.Connection = myCon;
myCommand.Parameters.AddWithValue("@Stud_Id", txtStudid.Text);
myCommand.Parameters.AddWithValue("@First_Name", txtFname.Text);
myCommand.Parameters.AddWithValue("@Last_Name", txtLname.Text);
myCommand.Parameters.AddWithValue("@Gender", txtGender.Text);
myCommand.Parameters.AddWithValue("@Department", txtDepartment.Text);
myCommand.Parameters.AddWithValue("@CGPA", txtCgpa.Text);
try {
myCon.Open();
if (MessageBox.Show("Are u sure to
update","Confirmation",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.
Yes) {
myCommand.ExecuteNonQuery();
MessageBox.Show("Record Updated","Update");
dataGridView1.Refresh();
}
myCon.Close();
}
catch(SqlException ex){
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e){
myCommand.CommandText = "Delete from Student where Stud_Id=@Stud_Id";

pg. 46
myCommand.Connection = myCon;
try {
myCon.Open();
if(MessageBox.Show("Are u sure to
delete?","Confirmation",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.
Yes){
myCommand.ExecuteNonQuery();
MessageBox.Show("Record deleted","Delete");
}
myCon.Close();
}
catch(SqlException ex){
MessageBox.Show(ex.ToString());}}}}
Activity: Adding, Saving, Updating, Deleting and Viewing Records using
the SqlDataAdapter class
Design:

pg. 47
Running:
Saving Records:

pg. 48
Viewing Records:

pg. 49
Updating Records:

pg. 50
pg. 51
Deleting Records:

pg. 52
pg. 53
Adding New Records:

pg. 54
Full Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace EmployeeInfo
{
public partial class Form1 : Form
{
public Form1()
{

pg. 55
InitializeComponent();
}
SqlConnection myCon = new SqlConnection("Data Source=DIRES;Initial
Catalog=Workers;Integrated Security=True");
public void Compute(){
double hr, payrate, total;
hr = Convert.ToDouble(txtHours.Text);
payrate = Convert.ToDouble(txtPayrate.Text);
total = hr * payrate;
txtTotalwage.Text = String.Concat(total);
if (total >= 10000)
txtStatus.Text = "High Earner";
else if (total >= 5000)
txtStatus.Text = "Medium";
else if (total < 5000)
txtStatus.Text = "Low Earner";
}
public void AddNew() {
txtEmpname.Text = "";
txtEmpid.Text = "";
cmbGender.Text = "";
txtHours.Text = "";
txtPayrate.Text = "";
txtTotalwage.Text = "";
txtStatus.Text = "";
}
private void btnAddNew_Click(object sender, EventArgs e)
{
AddNew();
}
public void Save() {

pg. 56
Compute();
SqlDataAdapter adapter = new SqlDataAdapter("Insert into
Employees(Emp_Name,Emp_Id,Gender,Hours_Worked,Pay_Rate,Total_Wage,Status)" +
"Values('" + txtEmpname.Text + "','" + txtEmpid.Text + "','" + cmbGender.Text + "','" +
txtHours.Text + "','" + txtPayrate.Text + "','" + txtTotalwage.Text + "','" + txtStatus.Text + "')",
myCon);
try
{
myCon.Open();
if (MessageBox.Show("Are u sure to save the entered record?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Record is saved", "Confirmation");
}
myCon.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Save();
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
txtEmpname.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtEmpid.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
cmbGender.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

pg. 57
txtHours.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
txtPayrate.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
txtTotalwage.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
txtStatus.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
}
public void ViewRecords() {
SqlDataAdapter adapter = new SqlDataAdapter("Select*From Employees", myCon);
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
private void btnView_Click(object sender, EventArgs e)
{
ViewRecords();
}
public void UpdateRecords() {
Compute();
SqlDataAdapter myadapter = new SqlDataAdapter("Update Employees set Emp_Name='" +
txtEmpname.Text + "',Gender='" + cmbGender.Text + "',Hours_Worked='" + txtHours.Text +
"',Pay_Rate='" + txtPayrate.Text + "',Total_Wage='" + txtTotalwage.Text + "',Status='" +
txtStatus.Text + "' where Emp_Id='" + txtEmpid.Text + "' ", myCon);
try
{
myCon.Open();
if (MessageBox.Show("Are u sure to update the selected record?", "Confirm",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
myadapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Record Updated", "Update");
}
myCon.Close();

pg. 58
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateRecords();
}
public void DeleteRecords() {
SqlDataAdapter myadapter = new SqlDataAdapter("Delete From Employees where Emp_Id='" +
txtEmpid.Text + "'", myCon);
try
{
myCon.Open();
if (MessageBox.Show("Are u sure to delete selcted record?", "Please Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
myadapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted", "Delete", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
if(dataGridView1.SelectedRows.Count>0){
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
}
myCon.Close();
}
catch (SqlException ex){
MessageBox.Show(ex.ToString());
}

pg. 59
}
private void btnDelete_Click(object sender, EventArgs e)
{
DeleteRecords();
}
private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
{
AddNew();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Save();
}
private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateRecords();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteRecords();
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
ViewRecords();
}
}
}

pg. 60
Activity: Create Login Form

Running

Confirmation

pg. 61
Calling another form

pg. 62
Coding For Login
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Login_Page
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DIRES;Initial
Catalog=Employee;Integrated Security=True;Pooling=False");
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select Role from Users Where User_Name = '" + textBox1.Text +
"' AND Password='" + textBox2.Text + "'";
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();

pg. 63
int count = 0;
String rname = null;
while (reader.Read())
{
rname = reader["Role"].ToString();
if (count == 0 && rname == "Admin")
{
MessageBox.Show("Login Success");
Administrator ad = new Administrator();
this.Hide();
ad.Show();
}
else if (count == 0 && rname == "Manager")
{
MessageBox.Show("Login Success");
Manager mn = new Manager();
this.Hide();
mn.Show();
}
else if (count > 0)
{

MessageBox.Show("Duplicate user acounts in your table");

}
else
{
MessageBox.Show("Password or User name is Incorrect");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();

}
}
}

Code for the Manager Form

using System;
using System.Collections.Generic;
using System.ComponentModel;

pg. 64
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Employee_Payrol_System
{
public partial class Manager_Page : Form
{
public Manager_Page()
{
InitializeComponent();
}
public void Compute()
{
double salary, allowance, overtime, pention, net_salary, gross_salary, tax;

salary = Convert.ToDouble(txtsalary.Text);
allowance = Convert.ToDouble(txtallowance.Text);
overtime = Convert.ToDouble(txtovertime.Text);
gross_salary = salary + allowance + overtime;
txtgrosssalary.Text = string.Concat(gross_salary);
pention = (salary * 7) / 100;
txtpention.Text = string.Concat(pention);

if (salary >= 10000)


{
tax = (salary * 25) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax-1500;
txtnetsalary.Text = string.Concat(net_salary);
}
else if (salary >= 7000)
{
tax = (salary * 20) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax-955;
txtnetsalary.Text = string.Concat(net_salary);
}
else if (salary >= 5000)
{
tax = (salary * 15) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax-565;
txtnetsalary.Text = string.Concat(net_salary);

pg. 65
}
else if (salary >= 3000)
{
tax = (salary * 12) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax-325;
txtnetsalary.Text = string.Concat(net_salary);
}
else if (salary >= 2000)
{
tax = (salary * 10) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax;
txtnetsalary.Text = string.Concat(net_salary);
}
else if (salary >= 1000)
{
tax = (salary * 8) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax;
txtnetsalary.Text = string.Concat(net_salary);
}
else if (salary <= 1000)
{
tax = (salary * 5) / 100;
txttax.Text = string.Concat(tax);
net_salary = gross_salary - pention - tax;
txtnetsalary.Text = string.Concat(net_salary);
}

}
SqlConnection conn = new SqlConnection("Data Source=DIRES;Initial
Catalog=Employee;Integrated Security=True;Pooling=False");
private void btnaddnew_Click(object sender, EventArgs e)
{
txtname.Text = "";
txtid.Text = "";
cmbmonth.Text = "";
txtsalary.Text = "";
txtallowance.Text = "";
txtovertime.Text = "";
txtgrosssalary.Text = "";
txtpention.Text = "";
txttax.Text = "";
txtnetsalary.Text = "";

pg. 66
}

private void addNewToolStripMenuItem_Click(object sender, EventArgs e)


{
txtname.Text = "";
txtid.Text = "";
cmbmonth.Text = "";
txtsalary.Text = "";
txtallowance.Text = "";
txtovertime.Text = "";
txtgrosssalary.Text = "";
txtpention.Text = "";
txttax.Text = "";
txtnetsalary.Text = "";
}

private void btnsave_Click(object sender, EventArgs e)


{
Compute();
SqlDataAdapter ada = new SqlDataAdapter("Insert into
Employe(Emp_Name,Emp_Id,Month,Salary,Allowance,Overtime,Gross_Salary,Net_salary,Penti
on,Tax)" +
"Values('" + txtname.Text + "','" + txtid.Text + "','" + cmbmonth.Text + "','" +
txtsalary.Text + "','" + txtallowance.Text + "','" + txtovertime.Text + "','" + txtgrosssalary.Text +
"','" + txtnetsalary.Text + "','" + txtpention.Text + "','" + txttax.Text + "')", conn);

try
{
conn.Open();
if (MessageBox.Show("Do you want to Save the record", "Conformation Window",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ada.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The record is Saved", "Saved", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
conn.Close();

}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());

}
}

pg. 67
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Compute();
SqlDataAdapter ada = new SqlDataAdapter("Insert into
Employe(Emp_Name,Emp_Id,Month,Salary,Allowance,Overtime,Gross_Salary,Net_salary,Penti
on,Tax)" +
"Values('" + txtname.Text + "','" + txtid.Text + "','" + cmbmonth.Text + "','" +
txtsalary.Text + "','" + txtallowance.Text + "','" + txtovertime.Text + "','" + txtgrosssalary.Text +
"','" + txtnetsalary.Text + "','" + txtpention.Text + "','" + txttax.Text + "')", conn);

try
{
conn.Open();
if (MessageBox.Show("Do you want to Save the record", "Conformation Window",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ada.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The record is Saved", "Saved", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
conn.Close();

}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());

}
}

private void updateToolStripMenuItem_Click(object sender, EventArgs e)


{
Compute();
SqlDataAdapter adapter = new SqlDataAdapter("update Employe set Emp_Name='" +
txtname.Text + "',Month='" + cmbmonth.Text + "'" +
",Salary='" + txtsalary.Text + "',Allowance='" + txtallowance.Text + "',Overtime='" +
txtovertime.Text + "'" +
",Gross_Salary='" + txtgrosssalary.Text + "',Net_Salary='" + txtnetsalary.Text +
"',Pention='" + txtpention.Text + "'" +
",Tax='" + txttax.Text + "' where Emp_Id='" + txtid.Text + "'", conn);
try
{
conn.Open();
if (MessageBox.Show("Do you want to Update ?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{

pg. 68
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The Record is Updated", "Updated Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show("Please Insert The Update", ex.ToString());

}
}

private void btnupdate_Click(object sender, EventArgs e)


{
Compute();
SqlDataAdapter adapter = new SqlDataAdapter("update Employe set Emp_Name='" +
txtname.Text + "',Month='" + cmbmonth.Text + "'" +
",Salary='" + txtsalary.Text + "',Allowance='" + txtallowance.Text + "',Overtime='" +
txtovertime.Text + "'" +
",Gross_Salary='" + txtgrosssalary.Text + "',Net_Salary='" + txtnetsalary.Text +
"',Pention='" + txtpention.Text + "'" +
",Tax='" + txttax.Text + "' where Emp_Id='" + txtid.Text + "'", conn);
try
{
conn.Open();
if (MessageBox.Show("Do you want to Update ?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The Record is Updated", "Updated Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show("Please Insert The Update", ex.ToString());

}
}

private void btndelete_Click(object sender, EventArgs e)


{
SqlDataAdapter adapter = new SqlDataAdapter("Delete from Employe where Emp_Id='"
+ txtid.Text + "'", conn);

pg. 69
try
{
conn.Open();
if (MessageBox.Show("Do you want to Delete the Record ?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The Record is Deleted", "Deleted Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
txtname.Text = "";
txtid.Text = "";
cmbmonth.Text = "";
txtsalary.Text = "";
txtallowance.Text = "";
txtovertime.Text = "";
txtgrosssalary.Text = "";
txtpention.Text = "";
txttax.Text = "";
txtnetsalary.Text = "";
}
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)


{
SqlDataAdapter adapter = new SqlDataAdapter("Delete from Employe where Emp_Id='"
+ txtid.Text + "'", conn);
try
{
conn.Open();
if (MessageBox.Show("Do you want to Delete the Record ?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
adapter.SelectCommand.ExecuteNonQuery();
MessageBox.Show("The Record is Deleted", "Deleted Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
txtname.Text = "";
txtid.Text = "";
cmbmonth.Text = "";
txtsalary.Text = "";
txtallowance.Text = "";

pg. 70
txtovertime.Text = "";
txtgrosssalary.Text = "";
txtpention.Text = "";
txttax.Text = "";
txtnetsalary.Text = "";
}
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}

private void btnview_Click(object sender, EventArgs e)


{
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Employe", conn);
DataTable tb = new DataTable();
adapter.Fill(tb);
dataGridView1.DataSource = tb;
}

private void displayToolStripMenuItem_Click(object sender, EventArgs e)


{
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Employe", conn);
DataTable tb = new DataTable();
adapter.Fill(tb);
dataGridView1.DataSource = tb;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)


{
if (e.RowIndex > -1)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

txtname.Text = row.Cells[0].Value.ToString();
txtid.Text = row.Cells[1].Value.ToString();
cmbmonth.Text = row.Cells[2].Value.ToString();
txtsalary.Text = row.Cells[3].Value.ToString();
txtallowance.Text = row.Cells[4].Value.ToString();
txtovertime.Text = row.Cells[5].Value.ToString();
txtgrosssalary.Text = row.Cells[6].Value.ToString();
txtnetsalary.Text = row.Cells[7].Value.ToString();
txtpention.Text = row.Cells[8].Value.ToString();

pg. 71
txttax.Text = row.Cells[9].Value.ToString();
}
}
}
}

pg. 72

You might also like