Saturday, 26 July 2014

Use File Upload Control in Gridview in asp.Net


File Upload Control inside Gridview


Description:-

In this example we explain that how to use fileupload control inside Gridview for uploading images or file to server. Or how to use fileupload control in gridview to upload image or file to server in asp.net.

In previous example we already explain that how to bind Dropdownlist inside gridview.

Here in this example we have one table called employee and have two field like empname and employee photo. In gridview footer row we are add one textbox footer for employee name and one file upload for employee photo and when click on submit button this footer rows data like employye name and employee photo are bind to the gridview.

Here we define RowDatabound event of the gridview so one by one row of the gridview is binded with empname and it's selected country and user can also change the employees country in the dropdownlist.

Dynamically Bind Data in Ajax Accordion Panel Bind Data to Accordion from databse

Restrict the size of File when Uploaded How to Restrict the size of File when uploaded by user



Default2.aspx:-

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

<!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 id="Head1" runat="server">
    <title>use File Upload inside Gridview ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grd_upldempphoto" runat="server" AutoGenerateColumns="False" ShowFooter="True"
            BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
            CellPadding="3" CellSpacing="2">
            <Columns>
                <asp:TemplateField HeaderText="S.No." ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <%#Container.DataItemIndex+1%>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp_Id">
                    <ItemTemplate>
                        <asp:Label ID="lblEmp_Id" runat="server" Text='<%#DataBinder.
                              Eval(Container.DataItem, "Emp_Id") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtEmp_Id" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp_Name">
                    <ItemTemplate>
                        <asp:Label ID="lblEmp_Name" runat="server" Text='<%#DataBinder.
                              Eval(Container.DataItem, "Emp_Name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtEmp_Name" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp_Photo">
                    <ItemTemplate>
                        <asp:Image ID="imgPhoto" runat="server" Width="100px" Height="120px" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "Emp_Photo") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:FileUpload ID="fUpload" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <FooterTemplate>
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_OnClick" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
        <asp:Label ID="lblMsg" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


Default2.aspx.cs:-

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

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=kiritdemo;Initial Catalog=Demo;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateGrid();
        }
    }
    protected void PopulateGrid()
    {
        DataSet ds = new DataSet();
        conn.Open();
        string cmdstr = "Select * from Employee";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        grd_upldempphoto.DataSource = ds;
        grd_upldempphoto.DataBind();
        conn.Close();
    }

    protected void btnUpload_OnClick(object sender, EventArgs e)
    {
        TextBox txtEmp_Id = (TextBox)grd_upldempphoto.FooterRow.FindControl("txtEmp_Id");
        TextBox txtEmp_Name = (TextBox)grd_upldempphoto.FooterRow.FindControl("txtEmp_Name");
        FileUpload fuploadFile = (FileUpload)grd_upldempphoto.FooterRow.FindControl("fUpload");
        Button btnUpload = (Button)grd_upldempphoto.FooterRow.FindControl("btnUpload");

        if (fuploadFile.HasFile)
        {
            string fileEmp_Name = fuploadFile.FileName;
            string exten = Path.GetExtension(fileEmp_Name);
            //here we have to restrict file type           
            exten = exten.ToLower();
            string[] acceptedFileTypes = new string[4];
            acceptedFileTypes[0] = ".jpg";
            acceptedFileTypes[1] = ".jpeg";
            acceptedFileTypes[2] = ".gif";
            acceptedFileTypes[3] = ".png";
            bool acceptFile = false;
            for (int i = 0; i <= 3; i++)
            {
                if (exten == acceptedFileTypes[i])
                {
                    acceptFile = true;
                }
            }
            if (!acceptFile)
            {
                lblMsg.Text = "The file you are trying to upload is not a permitted file type!";
            }
            else
            {
                //upload the file onto the server                  
                fuploadFile.SaveAs(Server.MapPath("~/Images/" + fileEmp_Name));

                conn.Open();
                string cmdstr = "insert into Employee(Emp_Id,Emp_Name,Emp_Photo) values(@Emp_Id,@Emp_Name,@photo)";
                SqlCommand cmd = new SqlCommand(cmdstr, conn);
                cmd.Parameters.AddWithValue("@Emp_Id", txtEmp_Id.Text);
                cmd.Parameters.AddWithValue("@Emp_Name", txtEmp_Name.Text);
                cmd.Parameters.AddWithValue("@photo", "Images/" + fileEmp_Name);
                cmd.ExecuteNonQuery();
                conn.Close();
                PopulateGrid();
            }
        }
    }
}


0 comments:

Post a Comment