File Uploading In ASP.NET

In this article you will learn the following things:

  • File Uploading
  • Dynamically handle button for SAVE (new record) and UPDATE (changes) saved data to the database.
  • Image display from image path from the database.

Note: Image not saved in table and image path store only table.

  1. Create an ASP.NET Empty Web Site and give name FileUpload.

    Asp.NET Empty website

  2. Right click on solution bar.

    Add new item

  3. Add a new Web Form.

    Web form

  4. Right click on Solution explorer and click New Folder option. Give name FRIENDIMAGES.

    add new folder

    We will store all images inside FRIENDIMAGES.
  5. Now switch back to DEFAULT.ASPX page, drag and drop HTML TABLE from TOOL BOX.

    Note: HTML tool box of controls located at bottom of toolbox.

    Add the following controls as per charts.

    Control Type Control ID Description
    Label lblFriend To display MemberID
    TextBox txtName To enter member name.
    Image imgFriend Friend Image to display.
    File Upload fuFriendImage Friend Image File Upload.
    TextBox txtPlace To enter place.
    TextBox txtMobile To enter mobile.
    Button btnSubmit Button to submit data.
    GridView gvMember Gridview to display data.
    Set following settings from properties:
    AutoGenerateSelectButton="True" Width="100%"

    Drag and drop above mentioned controls from TOOLBOX after html table.

  6. Add the following namespace in DEFAULT.ASPX.CS.
    1. using System.Data;   
    2. using System.Data.SqlClient;  
    3. using System.Configuration;  
    4. using System.IO;  
    Using System.Data: This namespace to access ADO.NET full functionalities.
    Using System.Data.SqlClient: This namespace to access SQL Server database.
    Using System.Configuration: To fetch connection string from web.config.
    Using System.IO: To work with file and folders.

  7. Table structure of tblFriends.
    1. CREATE TABLE [dbo].[tblFriends](  
    2.     [FriendID] [int] IDENTITY(1,1)NOT NULL,  
    3.     [FriendName] [varchar](50)NULL,  
    4.     [FriendImage] [varchar](500)NULL,  
    5.     [Place] [varchar](500)NULL,  
    6.     [Mobile] [varchar](20)NULL  
    7. )ON [PRIMARY]  
    8.   
    9. GO  
  8. ASPX code,

    DEFAULT.ASPX
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    2.     <!DOCTYPE html>  
    3.     <html xmlns="http://www.w3.org/1999/xhtml">  
    4.   
    5.     <head runat="server">  
    6.         <title></title>  
    7.         <style type="text/css">  
    8. .auto-style1 {  
    9.     text-align: center;  
    10. }  
    11.   
    12. .auto-style2 {  
    13.     width: 119px;  
    14.     height: 23px;  
    15.     text-align: left;  
    16. }  
    17.   
    18. .auto-style3 {  
    19.     height: 23px;  
    20. }  
    21.   
    22. .auto-style4 {  
    23.     width: 274px;  
    24. }  
    25.   
    26. .auto-style5 {  
    27.     height: 23px;  
    28.     width: 274px;  
    29. }  
    30.   
    31. .auto-style6 {  
    32.     text-align: left;  
    33. }  
    34.   
    35. .auto-style7 {  
    36.     text-align: center;  
    37.     height: 23px;  
    38. }  
    39.   
    40. .auto-style8 {  
    41.     text-align: center;  
    42.     height: 23px;  
    43.     font-size: x-large;  
    44.     font-weight: bold;  
    45.     text-decoration: underline;  
    46. }  
    47.   
    48. .auto-style9 {  
    49.     text-align: left;  
    50.     height: 239px;  
    51. }  
    52.   
    53. .auto-style10 {  
    54.     width: 274px;  
    55.     height: 239px;  
    56. }  
    57.   
    58. .auto-style11 {  
    59.     height: 239px;  
    60. }  
    61.         </style>  
    62.     </head>  
    63.   
    64.     <body>  
    65.         <form id="form1" runat="server">  
    66.             <div>  
    67.                 <table style="width:100%;">  
    68.                     <tr>  
    69.                         <td class="auto-style8" colspan="3">Friend Detail</td>  
    70.                     </tr>  
    71.                     <tr>  
    72.                         <td class="auto-style1"> </td>  
    73.                         <td class="auto-style4"> </td>  
    74.                         <td> </td>  
    75.                     </tr>  
    76.                     <tr>  
    77.                         <td class="auto-style6">  
    78.                             <asp:Label ID="Label1" runat="server" Text="Friend ID"></asp:Label>  
    79.                         </td>  
    80.                         <td class="auto-style4">  
    81.                             <asp:Label ID="lblMemberID" runat="server" Text="[FriendID]"></asp:Label>  
    82.                         </td>  
    83.                         <td> </td>  
    84.                     </tr>  
    85.                     <tr>  
    86.                         <td class="auto-style2">  
    87.                             <asp:Label ID="Label2" runat="server" Text="Name"></asp:Label>  
    88.                         </td>  
    89.                         <td class="auto-style5">  
    90.                             <asp:TextBox ID="txtName" runat="server" Width="250px"></asp:TextBox>  
    91.                         </td>  
    92.                         <td class="auto-style3"></td>  
    93.                     </tr>  
    94.                     <tr>  
    95.                         <td class="auto-style9">  
    96.                             <asp:Label ID="Label3" runat="server" Text="Image"></asp:Label>  
    97.                         </td>  
    98.                         <td class="auto-style10">  
    99.                             <asp:Image ID="imgFriend" runat="server" Height="194px" Width="189px" />  
    100.                             <br />  
    101.                             <asp:FileUpload ID="fuFriendImage" runat="server" />  
    102.                             <br />  
    103.                             <br /> </td>  
    104.                         <td class="auto-style11"></td>  
    105.                     </tr>  
    106.                     <tr>  
    107.                         <td class="auto-style6">  
    108.                             <asp:Label ID="Label4" runat="server" Text="Place"></asp:Label>  
    109.                         </td>  
    110.                         <td class="auto-style4">  
    111.                             <asp:TextBox ID="txtPlace" runat="server"></asp:TextBox>  
    112.                         </td>  
    113.                         <td> </td>  
    114.                     </tr>  
    115.                     <tr>  
    116.                         <td class="auto-style6">  
    117.                             <asp:Label ID="Label5" runat="server" Text="Mobile"></asp:Label>  
    118.                         </td>  
    119.                         <td class="auto-style4">  
    120.                             <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>  
    121.                         </td>  
    122.                         <td> </td>  
    123.                     </tr>  
    124.                     <tr>  
    125.                         <td class="auto-style1"> </td>  
    126.                         <td class="auto-style4"> </td>  
    127.                         <td> </td>  
    128.                     </tr>  
    129.                     <tr>  
    130.                         <td class="auto-style1" colspan="2">  
    131.                             <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" /> </td>  
    132.                         <td> </td>  
    133.                     </tr>  
    134.                     <tr>  
    135.                         <td class="auto-style7"></td>  
    136.                         <td class="auto-style5"></td>  
    137.                         <td class="auto-style3"></td>  
    138.                     </tr>  
    139.                     <tr>  
    140.                         <td class="auto-style1"> </td>  
    141.                         <td class="auto-style4"> </td>  
    142.                         <td> </td>  
    143.                     </tr>  
    144.                     <tr>  
    145.                         <td class="auto-style1" colspan="3">  
    146.                             <asp:GridView ID="gvFriend" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" Width="100%" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnSelectedIndexChanged="gvFriend_SelectedIndexChanged">  
    147.                                 <Columns>  
    148.                                     <asp:BoundField DataField="FriendID" HeaderText="Friend ID." ItemStyle-Width="150" />  
    149.                                     <%--<asp:TemplateField HeaderText="FriendID" InsertVisible="False" SortExpression="FriendID">  
    150. <ItemTemplate>  
    151. <asp:Label ID="Label1" runat="server" Text='<%# Bind("FriendID") %>'></asp:Label>  
    152.                                         </ItemTemplate>  
    153.                                         </asp:TemplateField>--%>  
    154.                                         <asp:TemplateField HeaderText="FriendName" SortExpression="FriendName">  
    155.                                             <ItemTemplate>  
    156.                                                 <asp:Label ID="lblFriendName" runat="server" Text='<%# Bind("FriendName") %>'></asp:Label>  
    157.                                             </ItemTemplate>  
    158.                                         </asp:TemplateField>  
    159.                                         <asp:TemplateField HeaderText="FriendImage" SortExpression="FriendImage">  
    160.                                             <ItemTemplate>  
    161.                                                 <asp:Image ID="imgFrnd" runat="server" ImageUrl='<%# Bind("FriendImage") %>' Width="50"></asp:Image>  
    162.                                             </ItemTemplate>  
    163.                                         </asp:TemplateField>  
    164.                                         <asp:TemplateField HeaderText="Place" SortExpression="Place">  
    165.                                             <ItemTemplate>  
    166.                                                 <asp:Label ID="lblPlace" runat="server" Text='<%# Bind("Place") %>'></asp:Label>  
    167.                                             </ItemTemplate>  
    168.                                         </asp:TemplateField>  
    169.                                         <asp:TemplateField HeaderText="Mobile" SortExpression="Mobile">  
    170.                                             <ItemTemplate>  
    171.                                                 <asp:Label ID="lblMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>  
    172.                                             </ItemTemplate>  
    173.                                         </asp:TemplateField>  
    174.                                 </Columns>  
    175.                                 <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
    176.                                 <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
    177.                                 <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
    178.                                 <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
    179.                                 <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
    180.                                 <SortedAscendingCellStyle BackColor="#FFF1D4" />  
    181.                                 <SortedAscendingHeaderStyle BackColor="#B95C30" />  
    182.                                 <SortedDescendingCellStyle BackColor="#F1E5CE" />  
    183.                                 <SortedDescendingHeaderStyle BackColor="#93451F" /> </asp:GridView>  
    184.                         </td>  
    185.                     </tr>  
    186.                     <tr>  
    187.                         <td class="auto-style1"> </td>  
    188.                         <td class="auto-style4"> </td>  
    189.                         <td> </td>  
    190.                     </tr>  
    191.                     <tr>  
    192.                         <td class="auto-style1"> </td>  
    193.                         <td class="auto-style4"> </td>  
    194.                         <td> </td>  
    195.                     </tr>  
    196.                     <tr>  
    197.                         <td class="auto-style1"> </td>  
    198.                         <td class="auto-style4"> </td>  
    199.                         <td> </td>  
    200.                     </tr>  
    201.                 </table>  
    202.             </div>  
    203.         </form>  
    204.     </body>  
    205.   
    206.     </html>  
  9. C# Code - Code Behind

    DEFAULT.ASPX.CS
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.UI;  
    6. using System.Web.UI.WebControls;  
    7. using System.Data;  
    8. using System.Data.SqlClient;  
    9. using System.Configuration;  
    10. using System.IO;  
    11.   
    12. public partial class _Default : System.Web.UI.Page  
    13. {  
    14.   
    15.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
    16.   
    17.     protected void Page_Load(object sender, EventArgs e)  
    18.     {  
    19.   
    20.         if (!IsPostBack)  
    21.         {  
    22.             BindGridView();  
    23.         }  
    24.   
    25.     }  
    26.   
    27.     /// <summary>  
    28.     /// Friend Submission code.  
    29.     /// </summary>  
    30.     /// <param name="sender"></param>  
    31.     /// <param name="e"></param>  
    32.     protected void btnSave_Click(object sender, EventArgs e)  
    33.     {  
    34.   
    35.         if (btnSave.Text.ToLower() == "save")  
    36.         {  
    37.           
    38.   
    39.         if (fuFriendImage.HasFile)  
    40.         {  
    41.   
    42.             string FileName = Path.GetFileName(fuFriendImage.PostedFile.FileName);  
    43.   
    44.               
    45.             //Save files to disk  
    46.   
    47.             fuFriendImage.SaveAs(Server.MapPath("FriendImages/" + FileName));  
    48.   
    49.               
    50.   
    51.             SqlConnection con = new SqlConnection(ConStr);  
    52.             con.Open();  
    53.             SqlCommand cmd = new SqlCommand("Insert into tblFriends (FriendName,FriendImage,Place,Mobile) Values(@FriendName,@FriendImage,@Place,@Mobile)", con);  
    54.             cmd.Parameters.AddWithValue("@FriendName", txtName.Text);  
    55.             cmd.Parameters.AddWithValue("@FriendImage""Friendimages/"+FileName);  
    56.             cmd.Parameters.AddWithValue("@Place", txtPlace.Text);  
    57.             cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);  
    58.             cmd.ExecuteNonQuery();  
    59.             BindGridView();  
    60.         }  
    61.         else  
    62.         {  
    63.             Response.Write("<script>alert('Please, select image file.')</script>");  
    64.         }  
    65.         }  
    66.   
    67.   
    68.         if (btnSave.Text.ToLower() == "update")  
    69.         {  
    70.   
    71.   
    72.             if (fuFriendImage.HasFile)  
    73.             {  
    74.   
    75.                 string FileName = Path.GetFileName(fuFriendImage.PostedFile.FileName);  
    76.   
    77.   
    78.                 //Save files to disk  
    79.   
    80.                 fuFriendImage.SaveAs(Server.MapPath("FriendImages/" + FileName));  
    81.   
    82.   
    83.   
    84.                 SqlConnection con = new SqlConnection(ConStr);  
    85.                 con.Open();  
    86.                 SqlCommand cmd = new SqlCommand("update tblFriends set FriendName =@FriendName ,FriendImage = @FriendImage,Place = @Place ,Mobile =@Mobile where FriendID = "+Convert.ToInt16(lblMemberID.Text), con);  
    87.                 cmd.Parameters.AddWithValue("@FriendName", txtName.Text);  
    88.                 cmd.Parameters.AddWithValue("@FriendImage""Friendimages/" + FileName);  
    89.                 cmd.Parameters.AddWithValue("@Place", txtPlace.Text);  
    90.                 cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);  
    91.                 cmd.ExecuteNonQuery();  
    92.   
    93.                 btnSave.Text = "Save";  
    94.                 BindGridView();  
    95.             }  
    96.             else  
    97.             {  
    98.                 Response.Write("<script>alert('Please, select image file.')</script>");  
    99.             }  
    100.         }  
    101.   
    102.   
    103.       
    104.     }  
    105.   
    106.   
    107.     /// <summary>  
    108.     /// To load data into grid view  
    109.     /// </summary>  
    110.     public void BindGridView()  
    111.     {  
    112.   
    113.         SqlConnection con = new SqlConnection(ConStr);  
    114.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblFriends", ConStr);  
    115.         DataSet ds = new DataSet();  
    116.         da.Fill(ds, "FriendTable");  
    117.         gvFriend.DataSource = ds;  
    118.         gvFriend.DataBind();  
    119.         clearTextBox();  
    120.     }  
    121.   
    122.     protected void gvFriend_SelectedIndexChanged(object sender, EventArgs e)  
    123.     {  
    124.         //Accessing BoundField Column  
    125.         lblMemberID.Text = gvFriend.SelectedRow.Cells[1].Text;  
    126.   
    127.         //Accessing TemplateField Column controls  
    128.         txtName.Text = (gvFriend.SelectedRow.FindControl("lblFriendName"as Label).Text;  
    129.         imgFriend.ImageUrl = (gvFriend.SelectedRow.FindControl("imgFrnd"as Image).ImageUrl;  
    130.         txtPlace.Text = (gvFriend.SelectedRow.FindControl("lblPlace"as Label).Text;  
    131.         txtMobile.Text = (gvFriend.SelectedRow.FindControl("lblMobile"as Label).Text;  
    132.         btnSave.Text = "Update";  
    133.   
    134.     }  
    135.   
    136.     protected void clearTextBox()  
    137.     {  
    138.         lblMemberID.Text = "[Member ID]";  
    139.         txtMobile.Text = string.Empty;  
    140.         txtName.Text = string.Empty;  
    141.         txtPlace.Text = string.Empty;  
    142.         imgFriend.ImageUrl = string.Empty;  
    143.   
    144.     }  
    145.   
    146. }  
  10. Our FileUpload Module User Interface (UI)

    Friend Detail

  11. Update state of application: When you select row of gridview it willchange caption of button as UPDATE otherwise button caption will SAVE.

    Update state

Please feel free to ask any question related to this article.