Site icon ParallelCodes

Making a Simple ASP.NET website

aspnet website png

Hi friends, today I will be sharing a basic asp.net website application code. To be more specific it’s  little more than beginner level. I will be showing how to add data in sql server database using .net website. This example will be using some basic Student info and add it to database. You will using the fileupload option provided in asp.net website to add a Student Profile Pic. The post consist of 2 pages and in the next page, I will using bootstrap css to style page and gridview to display student Info fetched from sql server database. And Image to display pic from path.

So let’s get started.

Software used :

  1. Visual studio 2008
  2. SQL server express 2005 (You can always use higher version, no worries).

First of all, in SQL server management studio create database with name “SimpleAsp”  and run following script :

Script for creation of database and it’s table : 

 

Create database [SimpleAsp]
Create database [SimpleAsp]
USE [SimpleAsp]
GO
/****** Object: Table [dbo].[StudentInfo] Script Date: 03/24/2016 23:52:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[StudentInfo](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [StudentName] [nvarchar](50) NOT NULL,
 [Class] [nvarchar](50) NOT NULL,
 [DOB] [datetime] NOT NULL,
 [StudentRollNo] [int] NOT NULL,
 [StudentAddress] [nvarchar](50) NOT NULL,
 [Gender] [nvarchar](50) NOT NULL,
 [StudentImage] [nvarchar](max) NOT NULL,
 [OnDate] [datetime] NOT NULL
) ON [PRIMARY]

 

Now create a asp.net website in Visual Studio (i’m using Visual Studio 2008 and .NET framework 3.5, you can use any). Open the web.config file and make a new connection string as below :

Web.Config:

This will be under the configuration node in your config file. And data source is the connection name to sql server. It can be found over here :

In web.config file add following code to save our data source name. The following lines will be under <configuration> node of our web.config file.

web.config:


<connectionStrings>
<add connectionString="Data Source=VIBES\SQLEXPRESS;Initial Catalog=SimpleAsp;Persist Security Info=True;User ID=hitesh;Password=789" name="db_Connection"/>
</connectionStrings>

And now open your default.aspx page (create it, if it’s not created) and edit it as :

Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Student Info</title>
 <style type="text/css">
 body
 {
 font-family: Calibri;
 font-size: 20px;
 }
 input[type=text], textarea, select
 {
 padding: 5px;
 }
 input[type=text]:hover, textarea:hover, select:focus
 {
 background-color: #ffff80;
 }
 input[type=submit]
 {
 padding: 5px 15px;
 text-transform: capitalize;
 background-color: #282828;
 color: #fff;
 font-size: 16px;
 border: solid 2px #282828;
 }
 input[type=submit]:hover
 {
 background-color: #fff;
 color: #282828;
 border: solid 2px #282828;
 }
 .btn-default
 {
 height: 26px;
 }
 </style>
</head>
<body>
 <form id="form1" runat="server">
 <div style="text-align: center">
 <table style="width: 100%">
 <tr>
 <td align="center">
 <table cellspacing="10" style="width: auto">
 <tr>
 <td colspan="2" align="center">
 <h1>
 </h1>
 </td>
 </tr>
 <tr>
 <td align="right">
 Student Name :
 </td>
 <td>
 <asp:TextBox runat="server" ID="txtStudentname" />
 <asp:RequiredFieldValidator runat="server" ControlToValidate="txtstudentname" ErrorMessage="*" />
 </td>
 </tr>
 <tr>
 <td align="right">
 Student Class :
 </td>
 <td>
 <asp:TextBox runat="server" ID="txtstudentclass" />
 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtstudentclass"
 ErrorMessage="*" />
 </td>
 </tr>
 <tr>
 <td align="right">
 Date of Birth :
 </td>
 <td>
 <asp:TextBox runat="server" ID="txtdob" placeholder="MM/DD/YYYY" />
</td>
 </tr>
 <tr>
 <td align="right">
 Student Address :
 </td>
 <td>
 <asp:TextBox runat="server" ID="txtaddress" TextMode="MultiLine" Height="100px" />
 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtaddress"
 ErrorMessage="*" />
 </td>
 </tr>
 <tr>
 <td align="right">
 Roll No :
 </td>
 <td>
 <asp:TextBox runat="server" ID="txtrollno" />
 <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtrollno"
 ErrorMessage="*" />
 </td>
 </tr>
 <tr>
 <td align="right">
 Student Image :
 </td>
 <td>
 <asp:FileUpload runat="server" ID="fileuploadforimage" />
 </td>
 </tr>
 <tr>
 <td align="right">
 Gender :
 </td>
 <td>
 <asp:DropDownList runat="server" ID="ddgender">
 <asp:ListItem Enabled="true" Text=" " Value=" " />
 <asp:ListItem Enabled="true" Text="Female" Value="Female" />
 <asp:ListItem Enabled="true" Text="Male" Value="Male" />
 </asp:DropDownList>
 </td>
 </tr>
 <tr>
 <td align="center" colspan="2">
 <asp:Button runat="server" ID="btnadd" Text="Add" OnClick="btnadd_Click" />
 &nbsp;&nbsp;
 <asp:Button runat="server" ID="Button1" Text="Clear" />
 </td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 <hr />
 <asp:Label runat="server" ID="lblinfo" />
 </div>
 </form>
</body>
</html>

And in the code file of the default page add following things :

Default.aspx.cs :

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data.Sql;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
 static String connectionString = ConfigurationManager.ConnectionStrings["db_Connection"].ConnectionString.ToString();
 SqlConnection con = new SqlConnection(connectionString);
 SqlCommand cmd;
 SqlDataAdapter dataAdapter;
 SqlDataReader reader;
 protected void Page_Load(object sender, EventArgs e)
 {
}
 protected void btnadd_Click(object sender, EventArgs e)
 {
 try
 {
 string strFileName = Path.GetFileName(fileuploadforimage.FileName); //fileupload1 is the <asp:fileupload ID
 fileuploadforimage.SaveAs(Server.MapPath("~/UploadedImages/" + strFileName + ""));
 String path = "~/UploadedImages/" + strFileName;
cmd = new SqlCommand("Insert into StudentInfo (StudentName,Class,DOB,StudentRollNo,StudentAddress,Gender,StudentImage,OnDate)
 values (@StudentName,@Class,@DOB,@StudentRollNo,@StudentAddress,@Gender,@StudentImage,@OnDate)", con);
 cmd.Parameters.AddWithValue("@StudentName", txtStudentname.Text.ToString());
 cmd.Parameters.AddWithValue("@Class", txtstudentclass.Text.ToString());
 cmd.Parameters.AddWithValue("@DOB", txtdob.Text.ToString());
 cmd.Parameters.AddWithValue("@StudentRollNo", txtrollno.Text.ToString());
 cmd.Parameters.AddWithValue("@StudentAddress", txtaddress.Text.ToString());
 cmd.Parameters.AddWithValue("@Gender", ddgender.Text.ToString());
 cmd.Parameters.AddWithValue("@StudentImage", path);
 cmd.Parameters.AddWithValue("@OnDate", System.DateTime.Now);
 if (con.State == ConnectionState.Closed)
 con.Open();
 cmd.ExecuteNonQuery();
 cmd.Dispose();
 lblinfo.Text = "Added Successfully";
 }
 catch (Exception ex)
 {
 lblinfo.Text = ex.Message.ToString();
 }
 }
}

Make a folder named UploadedImages.

Your project should like this :

The final page looks something like this :

This is a continuation of my post on making a simple asp.net website.

Make a new folder named css in your project folder and add bootstrap.css file in this folder. You can download bootstrap from here . It will help in designing the website. Next we will be adding Update and delete button. And an Image to view the Profile pic of student. Also a gridview with pagination to view the data present in the database and a button in gridview itself to be used. The page will be styled using bootstrap as mentioned before and it will be a responsive page meaning you can  view the page on any screen you want.

So let’s get started. Open the Default.aspx and change it as following :

Default.aspx :

 


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Info</title>
<link href="Css/bootstrap.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body,h1
{
font-family: Calibri;
margin: 0;
margin-bottom:5px;
padding: 0;
}
html, body
{
margin: 0;
padding: 0;
}
td > span
{
background-color: #464646;
padding: 5px 10px;
color: White;
margin: 2px;
border-radius: 5px;
}
td > a
{
background-color: #f9575b;
padding: 5px 10px;
color: White;
margin: 2px;
border-radius: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h1 style="width: 100%; text-align: center; background-color: #3c3c3c; color: #fff;">
ASP.NET</h1>
<div class="row">
<div class="col-lg-4">
<table class="table table-condensed">
<tr>
<td align="right">
Student Id :
</td>
<td>
<asp:TextBox runat="server" ID="txtid" Enabled="false" />
</td>
</tr>
<tr>
<td align="right">
Student Name :
</td>
<td>
<asp:TextBox runat="server" ID="txtStudentname" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtstudentname" ErrorMessage="*" />
</td>
</tr>
<tr>
<td align="right">
Student Class :
</td>
<td>
<asp:TextBox runat="server" ID="txtstudentclass" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtstudentclass"
ErrorMessage="*" />
</td>
</tr>
<tr>
<td align="right">
Date of Birth :
</td>
<td>
<asp:TextBox runat="server" ID="txtdob" placeholder="MM/DD/YYYY" />
</td>
</tr>
<tr>
<td align="right">
Student Address :
</td>
<td>
<asp:TextBox runat="server" ID="txtaddress" TextMode="MultiLine" Height="100px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtaddress"
ErrorMessage="*" />
</td>
</tr>
<tr>
<td align="right">
Roll No :
</td>
<td>
<asp:TextBox runat="server" ID="txtrollno" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtrollno"
ErrorMessage="*" />
</td>
</tr>
<tr>
<td align="right">
Student Image :
</td>
<td>
<asp:FileUpload runat="server" ID="fileuploadforimage" />
</td>
</tr>
<tr>
<td align="right">
Gender :
</td>
<td>
<asp:DropDownList runat="server" ID="ddgender">
<asp:ListItem Enabled="true" Text=" " Value=" " />
<asp:ListItem Enabled="true" Text="Female" Value="Female" />
<asp:ListItem Enabled="true" Text="Male" Value="Male" />
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button runat="server" ID="btnadd" Text="Add" OnClick="btnadd_Click" CssClass="btn btn-success" />
&nbsp;&nbsp;
<asp:Button runat="server" ID="btnupdate" Text="Update" OnClick="btnupdate_Click"
CssClass="btn btn-primary" />
&nbsp;&nbsp;
<asp:Button runat="server" ID="btndelete" Text="Delete" OnClick="btndelete_Click"
CssClass="btn btn-danger" />
&nbsp;&nbsp;
<asp:Button runat="server" ID="Button1" Text="Clear" OnClick="Button1_Click" CssClass="btn btn-default" />
</td>
</tr>
</table>
</div>
<div class="col-lg-8" style="overflow: scroll">
<div class="row">
<div class="col-lg-12" style="text-align: left">
&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
<asp:Image runat="server" ID="proImg" Width="150px" Height="150px" />
<br />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<br />
<h3>
Current Data in database :
</h3>
<hr />
<asp:GridView runat="server" ID="datagrid" UseAccessibleHeader="true" OnRowCommand="datagridview_RowCommand"
CssClass="table table-bordered" OnPageIndexChanging="datagridview_PageIndexChanging"
BorderWidth="1px" BorderColor="Black" AllowPaging="True" PageSize="4" PagerSettings-Mode="NumericFirstLast"
Font-Size="Smaller">
<Columns>
<asp:ButtonField ButtonType="Button" HeaderText="ClickHere" Text="ViewDetails" CommandName="ViewDetails"
ControlStyle-BackColor="#507CD1" ControlStyle-ForeColor="White" ControlStyle-Font-Size="15px">
<ControlStyle BackColor="#507CD1" Font-Size="15px" ForeColor="White"></ControlStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
</div>
</div>
</div>
<br />
</div>
<asp:Label runat="server" ID="lblinfo" />
</form>
</body>
</html>

And change the coding file as following :

Default.aspx.cs :


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data.Sql;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
static String connectionString = ConfigurationManager.ConnectionStrings["db_Connection"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd;
SqlDataAdapter dataAdapter;
SqlDataReader reader;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
DataGridFill();
}
public void DataGridFill()
{
try
{
cmd = new SqlCommand("Select * from StudentInfo", con);
if (con.State == ConnectionState.Closed)
con.Open();
dataAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "StudentInfo");
datagrid.DataSource = ds.Tables[0];
datagrid.DataBind();

}
catch (Exception ex)
{
lblinfo.Text = ex.Message.ToString();
}
}

protected void datagridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
datagrid.PageIndex = e.NewPageIndex;
DataGridFill();
}

protected void datagridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "ViewDetails")
{
int rowno = Int32.Parse(e.CommandArgument.ToString()); // It is the rowno of which the user as clicked
txtid.Text = datagrid.Rows[rowno].Cells[1].Text.ToString();
txtStudentname.Text = datagrid.Rows[rowno].Cells[2].Text.ToString();
txtstudentclass.Text = datagrid.Rows[rowno].Cells[3].Text.ToString();
txtdob.Text = datagrid.Rows[rowno].Cells[4].Text.ToString();
txtrollno.Text = datagrid.Rows[rowno].Cells[5].Text.ToString();
txtaddress.Text = datagrid.Rows[rowno].Cells[6].Text.ToString();
ddgender.Text = datagrid.Rows[rowno].Cells[7].Text.ToString();
proImg.ImageUrl = datagrid.Rows[rowno].Cells[8].Text.ToString();
}
}
catch (Exception ex)
{
lblinfo.Text = ex.Message.ToString();
}

}
protected void btnadd_Click(object sender, EventArgs e)
{
try
{
string strFileName = Path.GetFileName(fileuploadforimage.FileName); //fileupload1 is the <asp:fileupload ID
fileuploadforimage.SaveAs(Server.MapPath("~/UploadedImages/" + strFileName + ""));
String path = "~/UploadedImages/" + strFileName;

cmd = new SqlCommand("Insert into StudentInfo (StudentName,Class,DOB,StudentRollNo,StudentAddress,Gender
,StudentImage,OnDate) values (@StudentName,@Class,@DOB,@StudentRollNo,@StudentAddress,@Gender
,@StudentImage,@OnDate)", con);
cmd.Parameters.AddWithValue("@StudentName", txtStudentname.Text.ToString());
cmd.Parameters.AddWithValue("@Class", txtstudentclass.Text.ToString());
cmd.Parameters.AddWithValue("@DOB", txtdob.Text.ToString());
cmd.Parameters.AddWithValue("@StudentRollNo", txtrollno.Text.ToString());
cmd.Parameters.AddWithValue("@StudentAddress", txtaddress.Text.ToString());
cmd.Parameters.AddWithValue("@Gender", ddgender.Text.ToString());
cmd.Parameters.AddWithValue("@StudentImage", path);
cmd.Parameters.AddWithValue("@OnDate", System.DateTime.Now);

if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();

cmd.Dispose();
lblinfo.Text = "Added Successfully";
Clear();
DataGridFill();
}
catch (Exception ex)
{
lblinfo.Text = ex.Message.ToString();
}
}
protected void btnupdate_Click(object sender, EventArgs e)
{
try
{
cmd = new SqlCommand("Update StudentInfo set StudentName=@StudentName,Class=@Class,DOB=@DOB,
StudentRollNo=@StudentRollNo,StudentAddress=@StudentAddress,Gender=@Gender where Id = @Id",
 con);
cmd.Parameters.AddWithValue("@Id", txtid.Text.ToString());
cmd.Parameters.AddWithValue("@StudentName", txtStudentname.Text.ToString());
cmd.Parameters.AddWithValue("@Class", txtstudentclass.Text.ToString());
cmd.Parameters.AddWithValue("@DOB", txtdob.Text.ToString());
cmd.Parameters.AddWithValue("@StudentRollNo", txtrollno.Text.ToString());
cmd.Parameters.AddWithValue("@StudentAddress", txtaddress.Text.ToString());
cmd.Parameters.AddWithValue("@Gender", ddgender.Text.ToString());
cmd.Parameters.AddWithValue("@OnDate", System.DateTime.Now);

if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();

cmd.Dispose();
lblinfo.Text = "Updated Successfully";
Clear();
DataGridFill();
}
catch (Exception ex)
{
lblinfo.Text = ex.Message.ToString();
}
}

public void Clear()
{
txtid.Text = "";
txtStudentname.Text = "";
txtstudentclass.Text = "";
txtdob.Text = "";
txtrollno.Text = "";
txtaddress.Text = "";
ddgender.SelectedIndex = 0;
fileuploadforimage.Dispose();

}
protected void btndelete_Click(object sender, EventArgs e)
{
try
{
cmd = new SqlCommand("Delete from StudentInfo where Id = @Id", con);
cmd.Parameters.AddWithValue("@Id", txtid.Text.ToString());

if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();

cmd.Dispose();
lblinfo.Text = "Deleted Successfully";
Clear();
DataGridFill();
}
catch (Exception ex)
{
lblinfo.Text = ex.Message.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Clear();
}
}

On doing this you will be making page look like below :


Exit mobile version