<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CRUD_With_Images.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 400px;
/*text-align: center;*/
border: 5px black ridge;
margin: auto;
}
.auto-style2 {
width: 105px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="4" cellspacing="4" class="auto-style1">
<tr>
<td colspan="2">
<h1 style="text-align:center">EMPLOYEE CRUD APPLICATION</h1>
</td>
</tr>
<tr>
<td class="auto-style2">ID</td>
<td>
<asp:TextBox ID="IdTextBox" runat="server" Width="187px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="IdTextBox" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter employee id" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">NAME</td>
<td>
<asp:TextBox ID="NameTextBox" runat="server" Width="187px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="NameTextBox" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter employee name" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">AGE</td>
<td>
<asp:TextBox ID="AgeTextBox" runat="server" Width="187px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="AgeTextBox" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter employee age" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">GENDER</td>
<td>
<asp:DropDownList ID="GenderDropDownList" runat="server" Width="187px">
<asp:ListItem>Select Gender</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" InitialValue="Select Gender" ControlToValidate="GenderDropDownList" Display="Dynamic" ForeColor="Red" ErrorMessage="Please select any gender" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">DESIGNATION</td>
<td>
<asp:DropDownList ID="DesignationDropDownList" runat="server" Width="187px">
<asp:ListItem>Select Designation</asp:ListItem>
<asp:ListItem>Manager</asp:ListItem>
<asp:ListItem>Assistant Manager</asp:ListItem>
<asp:ListItem>Incharge</asp:ListItem>
<asp:ListItem>Operator</asp:ListItem>
<asp:ListItem>Director</asp:ListItem>
<asp:ListItem>PA</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" InitialValue="Select Designation" ControlToValidate="DesignationDropDownList" Display="Dynamic" ForeColor="Red" ErrorMessage="Please select any designation" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">SALARY</td>
<td>
<asp:TextBox ID="SalaryTextBox" runat="server" Width="187px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="SalaryTextBox" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter employee salary" SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">IMAGE</td>
<td>
<asp:Image ID="GetImage" runat="server" Height="70" Width="70" Visible="false"/><br/>
<asp:FileUpload ID="FileUpload1" runat="server" Width="187px"/><br/>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="InsertButton" runat="server" Text="INSERT" Height="33px" Width="84px" OnClick="InsertButton_Click" />
<asp:Button ID="UpdateButton" runat="server" Text="UPDATE" Height="33px" Width="84px" OnClick="UpdateButton_Click" />
<asp:Button ID="DeleteButton" runat="server" Text="DELETE" Height="33px" Width="84px" OnClick="DeleteButton_Click" OnClientClick="return confirm('Are you sure to delete ?')"/>
<asp:Button ID="ResetButton" runat="server" Text="RESET" Height="33px" Width="84px" OnClick="ResetButton_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" BackColor="Silver" ForeColor="Red" Font-Size="Larger"></asp:ValidationSummary>
</td>
</tr>
</table>
<br />
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" HorizontalAlign="Center" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField HeaderText="SELECT" ShowSelectButton="True"/>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="LabelId" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AGE">
<ItemTemplate>
<asp:Label ID="LabelAge" runat="server" Text='<%# Eval("age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GENDER">
<ItemTemplate>
<asp:Label ID="LabelGender" runat="server" Text='<%# Eval("gender") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DESIGNATION">
<ItemTemplate>
<asp:Label ID="LabelDesignation" runat="server" Text='<%# Eval("designation") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SALARY">
<ItemTemplate>
<asp:Label ID="LabelSalary" runat="server" Text='<%# Eval("salary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IMAGE">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("image_path") %>' Height="100" Width="100"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</form>
</body>
</html>
ABOVE FILE IS WebForm1.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CRUD_With_Images
{
public partial class WebForm1 : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
void ResetControls()
{
IdTextBox.Text = NameTextBox.Text = AgeTextBox.Text = SalaryTextBox.Text = "";
GenderDropDownList.ClearSelection();
DesignationDropDownList.ClearSelection();
Label1.Visible = false;
GetImage.Visible = false;
GridView1.SelectedIndex = -1;
}
protected void InsertButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
string filePath = Server.MapPath("images/");
string fileName = Path.GetFileName(FileUpload1.FileName);
string extension = Path.GetExtension(fileName);
HttpPostedFile postedFile = FileUpload1.PostedFile;
int size = postedFile.ContentLength;
if (FileUpload1.HasFile == true)
{
if (extension.ToLower() == ".jpg" || extension.ToLower() == ".jpeg" || extension.ToLower() == ".png")
{
if (size <= 1000000) //Means (size <= 1 MB)
{
string query2 = "SELECT * FROM emp WHERE Id=@Id";
SqlCommand cmd2 = new SqlCommand(query2,con);
cmd2.Parameters.AddWithValue("@Id",IdTextBox.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.HasRows == true)
{
Response.Write("<script>alert('Id already exists !!')</script>");
con.Close();
}
else
{
con.Close();
FileUpload1.SaveAs(filePath + fileName);
string path2 = "images/" + fileName;
try
{
string query = "INSERT INTO emp(Id,name,age,gender,designation,salary,image_path) VALUES(@Id,@name,@age,@gender,@desig,@salary,@img)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Id", IdTextBox.Text);
cmd.Parameters.AddWithValue("@name", NameTextBox.Text);
cmd.Parameters.AddWithValue("@age", AgeTextBox.Text);
cmd.Parameters.AddWithValue("@gender", GenderDropDownList.SelectedItem.Value);
cmd.Parameters.AddWithValue("@desig", DesignationDropDownList.SelectedItem.Value);
cmd.Parameters.AddWithValue("@salary", SalaryTextBox.Text);
cmd.Parameters.AddWithValue("@img", path2);
con.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Response.Write("<script>alert('Inserted Successfully !!')</script>");
BindGridView();
ResetControls();
Label1.Visible = false;
}
else
{
Response.Write("<script>alert('Insertion Failed !!')</script>");
}
con.Close();
}
catch (SqlException ex)
{
Response.Write("SqlException: " + ex.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
}
else
{
Label1.Text = "Length should be less than 1 MB";
Label1.Visible = true;
Label1.ForeColor = Color.Red;
}
}
else
{
Label1.Text = "Format not supported !!";
Label1.Visible = true;
Label1.ForeColor = Color.Red;
}
}
else
{
Label1.Text = "Please upload an image";
Label1.Visible = true;
Label1.ForeColor = Color.Red;
}
}
protected void ResetButton_Click(object sender, EventArgs e)
{
try
{
ResetControls();
}
catch (SqlException ex)
{
Response.Write("SqlException: " + ex.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
void BindGridView()
{
try
{
using(SqlConnection con = new SqlConnection(cs))
{
string query = "SELECT * FROM emp";
SqlDataAdapter sda = new SqlDataAdapter(query,con);
DataTable data = new DataTable();
sda.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
}
catch (SqlException ex)
{
Response.Write("SqlException: " + ex.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Label lblId = (Label)row.FindControl("LabelId");
Label lblName = (Label)row.FindControl("LabelName");
Label lblAge = (Label)row.FindControl("LabelAge");
Label lblGender = (Label)row.FindControl("LabelGender");
Label lblDesignation = (Label)row.FindControl("LabelDesignation");
Label lblSalary = (Label)row.FindControl("LabelSalary");
System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)row.FindControl("Image1");
IdTextBox.Text = lblId.Text;
NameTextBox.Text = lblName.Text;
AgeTextBox.Text = lblAge.Text;
GenderDropDownList.Text = lblGender.Text;
DesignationDropDownList.Text = lblDesignation.Text;
SalaryTextBox.Text = lblSalary.Text;
GetImage.ImageUrl = img.ImageUrl;
GetImage.Visible = true;
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
using(SqlConnection con = new SqlConnection(cs))
{
string filePath = Server.MapPath("images/");
string fileName = Path.GetFileName(FileUpload1.FileName);
string extension = Path.GetExtension(fileName);
HttpPostedFile postedFile = FileUpload1.PostedFile;
int size = postedFile.ContentLength;
string UpdatePath = "images/";
if (FileUpload1.HasFile == true)
{
if (extension.ToLower() == ".jpg" || extension.ToLower() == ".jpeg" || extension.ToLower() == ".png")
{
if (size <= 1000000) //Means (size <= 1 MB)
{
UpdatePath = UpdatePath + fileName;
FileUpload1.SaveAs(Server.MapPath(UpdatePath));
string query = "UPDATE emp SET name=@name,age=@age,gender=@gender,designation=@designation,salary=@salary,image_path=@image_path WHERE Id=@Id";
SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@Id",IdTextBox.Text);
cmd.Parameters.AddWithValue("@name",NameTextBox.Text);
cmd.Parameters.AddWithValue("@age",AgeTextBox.Text);
cmd.Parameters.AddWithValue("@gender",GenderDropDownList.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@designation",DesignationDropDownList.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@salary",SalaryTextBox.Text);
cmd.Parameters.AddWithValue("@image_path",UpdatePath);
con.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Response.Write("<script>alert('Updated Successfully !!')</script>");
BindGridView();
ResetControls();
Label1.Visible = false;
GetImage.Visible = false;
string DeletePath = Server.MapPath(GetImage.ImageUrl.ToString());
if (File.Exists(DeletePath) == true)
{
File.Delete(DeletePath);
}
}
else
{
Response.Write("<script>alert('Not Updated !!')</script>");
}
}
else
{
Label1.Text = "Length should be less than 1 MB";
Label1.Visible = true;
Label1.ForeColor = Color.Red;
}
}
else
{
Label1.Text = "Format not supported !!";
Label1.Visible = true;
Label1.ForeColor = Color.Red;
}
}
else
{
UpdatePath = GetImage.ImageUrl.ToString();
string query = "UPDATE emp SET name=@name,age=@age,gender=@gender,designation=@designation,salary=@salary,image_path=@image_path WHERE Id=@Id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Id", IdTextBox.Text);
cmd.Parameters.AddWithValue("@name", NameTextBox.Text);
cmd.Parameters.AddWithValue("@age", AgeTextBox.Text);
cmd.Parameters.AddWithValue("@gender", GenderDropDownList.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@designation", DesignationDropDownList.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@salary", SalaryTextBox.Text);
cmd.Parameters.AddWithValue("@image_path", UpdatePath);
con.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Response.Write("<script>alert('Updated Successfully !!')</script>");
BindGridView();
ResetControls();
Label1.Visible = false;
GetImage.Visible = false;
}
else
{
Response.Write("<script>alert('Not Updated !!')</script>");
}
}
}
}
catch (SqlException ex)
{
Response.Write("SqlException: " + ex.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
string query = "DELETE FROM emp WHERE Id=@Id";
SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@Id",IdTextBox.Text);
con.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Response.Write("<script>alert('Deleted Successfully !!')</script>");
BindGridView();
ResetControls();
Label1.Visible = false;
GetImage.Visible = false;
string DeletePath = Server.MapPath(GetImage.ImageUrl.ToString());
if (File.Exists(DeletePath) == true)
{
File.Delete(DeletePath);
}
}
}
}
catch (SqlException ex)
{
Response.Write("SqlException: " + ex.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
}
}
ABOVE FILE IS WebForm1.aspx.cs
CREATE TABLE [dbo].[emp] (
[Id] INT NOT NULL,
[name] VARCHAR (50) NOT NULL,
[age] INT NOT NULL,
[gender] VARCHAR (50) NOT NULL,
[designation] VARCHAR (50) NOT NULL,
[salary] INT NOT NULL,
[image_path] VARCHAR (MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Comments
Post a Comment