Student details CRUD operation in asp dot net technologies using c sharp and mssql

ASP.net Technologies is developed and design by microsoft by keeping secuity and effectiveness in mind it uses c# as its language .When ever we write code in asp.net technologies it is compiled to some html pages which is then deployed in IIS server which servers the pages to the user.

ASP.net gives powerful competition of PHP.But it is proved that ASP.net has edge in security over PHP. As it gives more security and flexibility due to which it is expensive in terms of money than PHP.Gulf nations and developed nations mainly uses asp.net technology for its development of web applications because it adds extra layer security in it.

In this article we will be completing student details system task. To know more about this task. Kindly read this post

Prerequisites :-

  1. Visual Studio (Community Version) download from here.
  2. MSSQL SERVER for download and install read this post.
  3. SQL Server Management Studio 
  4. W3.css to beauityfy webpage know more.

There are two methods for developing such application.

  1. Sequential Approach :- In this approach we will develop everything in one file.
  2. MVC Approach :- In  this approach we will use model view  controller approach in which three sub module will be created and each module is responsible for its task.

In this post we will discuss sequential approach in which we will write every thing in file.

STEP  1 :-   Create Database

Open Microsoft SQL Server Management Studio and then select Authentication to windows Authentication and then enter Server name .\SQLExpress then click connect.

Then right click on databases and then select new databases then enter database name as student_db and then click ok .Now student_db database is created.

STEP  2 :- Create Table

Right click on student_db and select new query .Now new query tab will be opened ,copy paste below code to create table in database.

CREATE TABLE [dbo].[student_table_new](
[student_id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_student_table_new] PRIMARY KEY CLUSTERED
(
[student_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

new table is created.

STEP  3 :-  Open Visual Studio and Create new Project .

Go to the file and then click new then select web from template then select empty web form . Enter Name as StudentDetails in Name section then click ok.

STEP  4 :- Set configuration String in web Configuration

on right hand side , click on solution explorer then click on web configuration. Then copy paste full code below to make connection with Student_db database.

<?xml version="1.0"?>

<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="studentconnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=student_db;Integrated Security=True;" providerName="System.Data.SqlClient" />

</connectionStrings>

</configuration>

STEP  5 :-  Creating new item

Right Click on Student Details in Solution explorer then go to ADD and now click on New item . Click on web form. Give name as Student Info.

STEP  6 :-  Writing Backend And Designer File

Open Student Info .aspx . Two files will be shown beside it one will be backend file and one will be designer file.

 Backend file will have extention as .cs and designer file will have extention as designer.cs .

 Firstly open designer file and copy paste below code. Below code uses w3.for CSS.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentInfo.aspx.cs" Inherits="StudentCheckingWithoutMVC.StudentInfo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta charset="utf-8">
<title>StudentDetails</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="width:100%;text-align:center">

<h1> Student Detail System</h1>

</div>

<div style="width:100%;align-content: center">
<asp:HiddenField runat="server" ID="hid_StudentID" />
<div style="margin:10px;display: inline-block;">Name : <asp:TextBox runat="server" ID="txtName" class="form-control"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Enter Name"
CssClass="lable-Error"></asp:RequiredFieldValidator></div>

<div style="margin:10px;display: inline-block;"> Address : <asp:TextBox runat="server" ID="txtAddress" class="form-control"></asp:TextBox> </div>

<div style="margin:10px;display: inline-block;"> Telephone : <asp:TextBox runat="server" ID="txtTelephone" class="form-control"></asp:TextBox></div>



<div style="margin:10px;display: inline-block;"> Standard : <asp:TextBox runat="server" ID="txtStandard" class="form-control"></asp:TextBox></div>

<div style="margin:10px;display: inline-block;" > Roll Number : <asp:TextBox runat="server" ID="txtRollNumber" class="form-control"></asp:TextBox></div>

</div>

<div class="w3-cell-row w3-center w3-padding">



<asp:Button ID="Button1" runat="server" name="submit" Text="Insert" class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Insert" OnClick="Insert_Click"/>

<asp:Button ID="update" runat="server" name="submit" Text="Update" class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Update" OnClick="update_Click"/>

<asp:Button ID="delete" runat="server" name="submit" Text="Delete" class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Delete" OnClick="delete_Click"/>

</div>


<asp:GridView ClientIDMode="Static" ID="datatable1" runat="server" AutoGenerateColumns="False" CssClass="w3-table-all w3-small" DataKeyNames="student_id"
CellPadding="0" border="0" class="datatable table table-striped table-bordered table-hover" OnRowDataBound="datatable1_RowDataBound" >
<Columns>
<asp:BoundField DataField="student_id" ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden" HeaderText="Category Code" SortExpression="Customer_Cd" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" SortExpression="Telephone" />
<asp:BoundField DataField="Roll_Number" HeaderText="Roll Number" />
<asp:BoundField DataField="Standard" HeaderText="Standard" />

</Columns>
</asp:GridView>


</div>
</form>
</body>
</html>

secondly open backend file and copy paste below code.In the below code we have written function for Insertion, Deletion and Listing.

 

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

namespace StudentCheckingWithoutMVC
{
public partial class StudentInfo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
getStudentList();
if (!IsPostBack)
{
if (Request.QueryString["Id"] != null)
{
#region "Check ID String"
getRecord(Convert.ToInt32(Request.QueryString["Id"]));

#endregion "Check Edit Permissions"
}

}
}
catch (Exception lo)
{

}

}

public void getRecord(int id)
{
SqlConnection con = new SqlConnection(Getconnectionstring("studentconnection"));
con.Open();


SqlCommand command = new SqlCommand("Select Name,Telephone,Address,Roll_Number,Standard,student_id from student_table where student_id="+id, con);

using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{

txtStandard.Text = reader.GetString(4);
txtTelephone.Text = reader.GetString(1);
txtName.Text = reader.GetString(0);
txtRollNumber.Text = reader.GetString(3);
txtAddress.Text = reader.GetString(2);
hid_StudentID.Value = reader.GetInt32(5).ToString();
//display retrieved record

}
}
else
{
Console.WriteLine("No data found.");
}

}

con.Close();
}

private void getStudentList()
{

using (SqlConnection con = new SqlConnection(Getconnectionstring("studentconnection")))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM student_table"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
datatable1.DataSource = dt;
datatable1.DataBind();
}
}
}
}
}

protected void Insert_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(Getconnectionstring("studentconnection"));
con.Open();
String insert = "INSERT INTO student_table(Name,Address,Telephone,Roll_Number,Standard) VALUES ('" + txtName.Text + "','" + txtAddress.Text + "','" + txtTelephone.Text + "','" + txtRollNumber.Text + "','" + txtStandard.Text + "')";
SqlCommand cmd= new SqlCommand(insert,con);
int m = cmd.ExecuteNonQuery();
if(m != 0)
{
Response.Write(" <script>alert('Data Inserted !!')</script> ");
}
else
{
Response.Write(" <script>alert('Data Inserted !!')</script> ");
}

con.Close();


clearAll();

}
catch (Exception e1)
{
}
}

protected void delete_Click(object sender, EventArgs e)
{

try
{
SqlConnection con = new SqlConnection(Getconnectionstring("studentconnection"));
con.Open();
String insert = "DELETE from student_table where student_id = "+hid_StudentID.Value;
SqlCommand cmd= new SqlCommand(insert,con);
int m = cmd.ExecuteNonQuery();
if(m != 0)
{
Response.Write(" <script>alert('Data Deleted !!')</script> ");
}
else
{
Response.Write(" <script>alert('Data Deleted!!')</script> ");
}

con.Close();


clearAll();

}

catch (Exception e1)
{
}
}

protected void update_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(Getconnectionstring("studentconnection"));
con.Open();
String insert = "UPDATE student_table set Name=" + txtName.Text + ",Address=" + txtAddress.Text + ",Telephone=" + txtTelephone.Text + ",Roll_Number=" + txtRollNumber.Text + ",Standard=" + txtStandard.Text + " where student_id = " + hid_StudentID.Value;
SqlCommand cmd = new SqlCommand(insert, con);
int m = cmd.ExecuteNonQuery();
if (m != 0)
{
Response.Write(" <script>alert('Data Updated !!')</script> ");
}
else
{
Response.Write(" <script>alert('Data Updated !!')</script> ");
}

con.Close();


clearAll();

}

catch (Exception e1)
{
}
}

public void clearAll()
{
txtName.Text = "";
txtAddress.Text = "";
txtStandard.Text = "";
txtRollNumber.Text = "";
txtTelephone.Text = "";
Response.Redirect("StudentInfo.aspx");
}

protected void datatable1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = "window.location.replace('StudentInfo.aspx?Id=" + e.Row.Cells[0].Text + "');";
e.Row.Attributes["style"] = "cursor:pointer";
}
}


public static string Getconnectionstring(string keyname)
{
string connection = string.Empty;
switch (keyname)
{
case "studentconnection":
connection = ConfigurationManager.ConnectionStrings["studentconnection"].ConnectionString;
break;

default:
break;
}
return connection;

}

}
}

STEP  7 :-  Run And Deployment

Click on green play button above to run the program.It will open chrome Tab with student details.You can now enter Student name,address,telephone etc.And can delete it after selecting from bottom.

 

All code it available at this GIT Repository here.

 

Errors which I face during development

Error 1 The type 'System.Data.Entity.DbContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. C:\Users\best\Documents\Visual Studio 2012\Projects\StudentChecking\Student.component\StudentBC.cs 12 35 Student.component


SaveChanges is not detecting as it is not referred properly

No connection string named 'student_dbEntities' could be found in the application config file.

Solution:-Kindly Check connection String properly. You can just copy paste above code to solve your errors.

Kindly Comments us if you are facing any problems while implementing .We will be happy to help you.If you want to develop or read simple CRUD Operation using MVC framework in asp.net technolgies you can read here .

 




Taher Ali Badnawarwala

Taher Ali, drives to create something special, He loves swimming ,family and AI from depth of his heart . He loves to write and make videos about AI and its usage


Leave a Comment


No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *