CRUD With Images In ASP.NET Web Forms | Image CRUD | CRUD Image | ASP.NET

 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.Configuration;

using System.Data;


namespace CRUD_APP_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)

                    {

                        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;


                            string query = "insert into emp 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();

                        }

                    }

                    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)

        {

            ResetControls();

        }


        void bindGridView()

        {

            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();

        }


        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 lblDesig = (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 = lblDesig.Text;

            SALARYTextBox.Text = lblSalary.Text;

            GetImage.ImageUrl = img.ImageUrl;

            GetImage.Visible = true;

        }


        protected void UPDATEButton_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;


            string UpdatePath = "images/";


            if (FileUpload1.HasFile == true)

            {

                if (extension.ToLower() == ".jpg" || extension.ToLower() == ".jpeg" || extension.ToLower() == ".png")

                {

                    if (size <= 1000000)

                    {

                        UpdatePath = UpdatePath + fileName;

                        FileUpload1.SaveAs(Server.MapPath(UpdatePath));


                        string query = "update emp set name=@name, age=@age, gender=@gender, designation=@desig, salary=@salary, image_path=@img 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("@desig",DESIGNATIONDropDownList.SelectedValue.ToString());

                        cmd.Parameters.AddWithValue("@salary",SALARYTextBox.Text);

                        cmd.Parameters.AddWithValue("@img",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>");

                        }

                        con.Close();

                    }

                    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=@desig, salary=@salary, image_path=@img 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("@desig", DESIGNATIONDropDownList.SelectedValue.ToString());

                cmd.Parameters.AddWithValue("@salary", SALARYTextBox.Text);

                cmd.Parameters.AddWithValue("@img", 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>");

                }

                con.Close();

            }

        }


        protected void DELETEButton_Click(object sender, EventArgs e)

        {

            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);

                }

            }

            else

            {

                Response.Write("<script>alert('Not Deleted !!')</script>");

            }

            con.Close();

        }

    }

}

Above File is CRUD_APP_WITH_IMAGES\WebForm1.aspx.cs







<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CRUD_APP_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: 500px;

            border:5px black ridge;

            margin:auto;

        }

        .auto-style2 {

            width: 25px;

        }

        .auto-style3 {

            width: 25px;

            height: 34px;

        }

        .auto-style4 {

            height: 34px;

        }

    </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-style3">ID</td>

                    <td class="auto-style4">

                        <asp:TextBox ID="IDTextBox" runat="server" Height="19px" Width="261px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Id is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="IDTextBox">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">NAME</td>

                    <td>

                        <asp:TextBox ID="NAMETextBox" runat="server" Height="19px" Width="261px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Name is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="NAMETextBox">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">AGE</td>

                    <td>

                        <asp:TextBox ID="AGETextBox" runat="server" Height="19px" Width="261px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Age is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="AGETextBox">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">GENDER</td>

                    <td>

                        <asp:DropDownList ID="GENDERDropDownList" runat="server" Height="19px" Width="264px">

                            <asp:ListItem>Select Gender</asp:ListItem>

                            <asp:ListItem>Male</asp:ListItem>

                            <asp:ListItem>Female</asp:ListItem>

                        </asp:DropDownList>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Gender is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="GENDERDropDownList" InitialValue="Select Gender">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">DESIGNATION</td>

                    <td>

                        <asp:DropDownList ID="DESIGNATIONDropDownList" runat="server" Height="19px" Width="264px">

                            <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" ErrorMessage="Designation is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="DESIGNATIONDropDownList" InitialValue="Select Designation">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">SALARY</td>

                    <td>

                        <asp:TextBox ID="SALARYTextBox" runat="server" Height="19px" Width="261px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Salary is a required field" ForeColor="Red" SetFocusOnError="True" ControlToValidate="SALARYTextBox">*</asp:RequiredFieldValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">IMAGE</td>

                    <td>

                        <asp:Image ID="GetImage" Height="70" Width="70" Visible="false" runat="server" />

                        <br />

                        <asp:FileUpload ID="FileUpload1" runat="server" />

                        <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" Height="37px" Text="INSERT" Width="91px" OnClick="INSERTButton_Click" />

&nbsp;<asp:Button ID="UPDATEButton" runat="server" Height="37px" Text="UPDATE" Width="91px" OnClick="UPDATEButton_Click" />

&nbsp;<asp:Button ID="DELETEButton" runat="server" Height="37px" Text="DELETE" Width="91px" OnClick="DELETEButton_Click" />

&nbsp;<asp:Button ID="RESETButton" runat="server" Height="37px" Text="RESET" Width="91px" OnClick="RESETButton_Click" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2">

                        <asp:ValidationSummary ID="ValidationSummary1" runat="server" BackColor="Silver" Font-Size="Larger" ForeColor="Red" />

                    </td>

                </tr>

            </table>

            <br/>

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" HorizontalAlign="Center" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">

                <Columns>

                    <asp:CommandField 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" Height="100" Width="100" ImageUrl='<%# Eval("image_path") %>' runat="server" />

                        </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 CRUD_APP_WITH_IMAGES\WebForm1.aspx

























Comments

Popular posts from this blog

AJAX Method Of jQuery AJAX In ASP.NET Web Forms | Learn ASP.NET Web Forms

List Box In ASP.NET Web Forms | ASP.NET ListBox | Web Forms Tutorial | ASP.NET

Display Auto Increment Value In Text Field After Insert To Database ASP.NET