Menu

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday, 31 August 2016

FileUpload control in asp.net


Introduction:

Create an example to  Upload Images using Fileupload Control in asp.net,The ASP.Net FileUpload control is a new web server control in ASP.Net 2.0 framework that provides the advanced functionality to the users to upload a file from their system to the online web server. It renders using HTML input type file control that appears as combination of two controls such as TextBox control and a Button control. The TextBox control sends the path of the file selected from the user's computer to the server, whereas button control provides the functionality to open a file-navigation dialog box. Users can navigate between the directories and files available on their system and select a file that they want to upload to the web server. The security feature of FileUpload control does not allow you to specify the file path dynamically and the users are also not allowed to type-in the file path in the textbox field available with FileUpload control. Users have to browse the file using file-navigation dialog box to select it for uploading.
Prerequisites for this tutorial:
  •     Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  •     Net FrameWork 4.0
Application:

Step1: Open Visual studio go toàfileàopen new website or project and clickàchoose language as c#, select web and click onasp.net empty website (or) Applicationàsave the file in your required directory at below paneàclick ok.
Step2: Right click on project name  in solution exploreràselect add clickàselect new item, a new template will open àchoose web form named as FileUpload in right pane and click ok.
Step3: To add FileUpload on page, go to toolboxàfind FileUpload à drag and drop on to designer page or source page.
Step4: Go to code behind file ... (FileUpload.aspx.cs)
1. FileUpload.aspx
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>File Upload </title>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,300italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css' />
    <style>
        body {
            font-family: 'Open Sans', sans-serif;
        }

        .content {
            width: 65%;
            margin: 0 auto;
            margin-top: 75px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="content">
            <b>Upload File:</b>
            <asp:FileUpload ID="FileUpload1" runat="server" />

            <br />
            <br/>

            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

            <br />

            <asp:Label ID="lblStatus" runat="server" />
        </div>
    </form>
</body>
</html>

Output:

DesignView:


2.FileUpload.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace gofaq
{
    public partial class fileupload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {

                if (FileUpload1.HasFile)
                {
                    try
                    {
                        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

                        string serverFolder = Server.MapPath("Upload\\");

                        if (!Directory.Exists(serverFolder))

                            Directory.CreateDirectory(serverFolder);

                        string serverFilePath = serverFolder + fileName;

                        FileUpload1.SaveAs(serverFilePath);

                        lblStatus.Text = "<b style='color:green'>File has been uploaded successfully!!!</b>";
                    }
                    catch (Exception)
                    {
                        lblStatus.Text = "<b style='color:red'>Some problem occurred while uploading the file. Please try after some time.</b>";
                    }
                }
                else
                {
                    lblStatus.Text = "<b style='color:red'>Please select a file to upload!!!</b>";
                }
            }           
        }
    }
}

//place this below code in btnUpload_click Event to Check File type And Max.Size(or) Length

        if (FileUpload1.HasFile)
            {

                try
                {

                    string fileType = FileUpload1.PostedFile.ContentType;

                    if (fileType == "image/jpeg" ||

                    fileType == "image/jpg" ||

                    fileType == "image/gif" ||

                    fileType == "image/png" ||

                    fileType == "image/bmp")
                    {

                        int fileSize = FileUpload1.PostedFile.ContentLength;

                        if (fileSize <= 50) //Max Size: 2MB
                        {

                            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

                            string serverFolder = Server.MapPath("Upload\\");

                            if (!Directory.Exists(serverFolder))

                                Directory.CreateDirectory(serverFolder);

                            string serverFilePath = serverFolder + fileName;

                            FileUpload1.SaveAs(serverFilePath);

                            lblStatus.Text = "<b style='color:green'>File has been uploaded successfully!!!</b>";

                        }

                        else
                        {

                            lblStatus.Text = "<b style='color:red'>Please select a file of max size 50kb only.</b>";

                        }

                    }

                    else
                    {

                        lblStatus.Text = "<b style='color:red'>Please select an image file only (Ex:*.jpg/*.jpeg/*.gif/*.png/*.bmp)</b>";

                    }

                }

                catch (Exception)
                {

                    lblStatus.Text = "<b style='color:red'>Some problem occurred while uploading the file. Please try after some time.</b>";

                }

            }

            else
            {

                lblStatus.Text = "<b style='color:red'>Please select a file to upload!!!</b>";

            }

Output:
Press CTRL+F5 or F5 to run the  page on server .

1.click on upload button with out selecting any file , it validates the file upload control.


2.click on choose file button it open your window’s Explorer and select appropriate image

3.click on upload button it saves the file into  appropriate folder  in project directory

4.To restrict the Type of file and Size,see the output below.Here ,I have uploaded a file with an extension of .txt

5. It alerts a message as like below

6. I have uploaded a file which is morethan 50kb,see what will happen 
6. it alerts a message "please select a file of max size 50kb only"
...for more information about previous tutorial please visit this link  ASP.Net Tutorials and Thank you for visiting my blog ,don't forget to comment on post and if you want daily updates Just  follow me in Google Plus.

Saturday, 20 August 2016

How to display employee data in Grid view using asp.net

Introduction:

The Grid View control is a powerful Data  control that allows you to display the collection of data, add sorting and paging, and perform inline editing. You can bind data to the Grid View control in two different ways that is, using the DataSourceID and the Data Source properties. In order to bind a data source control, set the DataSourceID property of the Grid View control to the ID value of the data source Control. Here, I explain step-by-step how to retrieve data in a Grid View.

Prerequisites for this tutorial:
  • Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  •  SQl server 2008 sp2/14/12

Database :(Sql Server 2008 sp2)

Table structures:

CREATE TABLE Department
(
    dept_Id INT NOT NULL PRIMARY KEY identity(1,1),
    Name VARCHAR(30) unique  
)
GO

CREATE TABLE Employee
(
    emp_Id INT NOT NULL primary key Identity(1,1),
    name varchar(50) unique,
    city varchar(50),
    dept_Id INT  FOREIGN KEY  REFERENCES
    Department(dept_Id) on update cascade on delete cascade
)
GO 

1.Department Table



2.Employee Table



Application:

Step1: To create Login page first you need to open visual studio and run as administrator.

Step2: Go to File

Step3: Right click on File and Go to new

Step4: Choose either website or Project

Step5: A new template will be opened

Step6: Choose the language as Visual C# in left side

Step7: Select ASP.NET Empty website in right side.

Step8: Finally, in bottom specify the website is http, ftpsystem or file system

Step9: Choose HTTP,specify the name of the website  at http://localhost/yourwebsitename andclick on ok. 

Step10: if you chosen new project, skip 8 -9 steps and just specify the Solution name and directory enough. You have successfully created.

Step11: Go to Solution Explorer, Right Click on your application and Add new web form named as Bingridview Form.

Step12: To add Gird view on page, go to toolbox -->find Grid view --> drag and drop on to designer page or source page.

Step13: Go to code behind file ... (bindgridview .aspx.cs)

1. Bingridview.aspx

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Display Data in Grid view</title>
     <style>
        .content {
            width: 45%;
            margin: 0 auto;
            margin-top: 75px;
        }
        th,td{
            Line-height: 26px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="content">
        <asp: GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="5" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
            <Columns>
                <asp:BoundField DataField="emp_Id" HeaderText="Employee ID" ItemStyle-HorizontalAlign="Center" />
                <asp:BoundField DataField="name" HeaderText="Employee Name" ItemStyle-HorizontalAlign="Center" />
                <asp:BoundField DataField="City" HeaderText="City" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" />
                <asp:BoundField DataField="Dept" HeaderText="Department Name" ItemStyle-HorizontalAlign="Center" />
            </Columns>
            <EditRowStyle BackColor="#999999"></EditRowStyle>

            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>

            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>

            <PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>

            <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>

            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

            <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>

            <SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>

            <SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>

            <SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

2.bindgridview.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace gofaq
{
    public partial class bindgridview : System.Web.UI.Page
    {

        SqlConnection con;
        protected void Page_Load(object sender, EventArgs e)
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            if (!Page.IsPostBack)
            {

                Display();
            }
        }
        void Display()
        {

            SqlCommand cmd = new SqlCommand("Select e.emp_Id, e.name, e.city, d.Name as Dept from Employee e,Department d Where e.dept_Id=d.dept_Id", con);
            if (con.State != ConnectionState.Open)
                con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            try
            {
                int RowCount = ds.Tables[0].Rows.Count;
                if (RowCount > 0)
                {
                    GridView1.DataSource = ds.Tables[0];
                    GridView1.DataBind();
                }
                else
                {
                    MessageBox("No data exists to display");
                }


            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (con.State != ConnectionState.Closed)
                    con.Close();
            }
        }
        public void MessageBox(string message)
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "Key", string.Format("alert('{0}');", message), true);
        }

    }

}

Output:
Press CTRL+F5 or F5 to run the  page on server .  

...for more information about previous tutorial please visit this link  ASP.Net Tutorials and Thank you for visiting my blog ,don't forget to comment on post and if you want daily updates Just  follow me in Google Plus.