Friday, 1 July 2016

File Upload in Gridview ASP.NET

          In this article we will learn  how to use file upload control in grid view in each row for uploading images or files to the database.
Step1 - First create a database table with the name  “FileUpload”.  And run the following script to create table.

CREATE TABLE [dbo].[FileUpload](
          [Studentid] [varchar](10) NULL,
          [name] [varchar](100) NULL,
          [photo] [varchar](100) NULL
) ON [PRIMARY]


Step2- Go to visual studio and add a webform (.aspx) to your website then write the following code in Designer side

Designer source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridFileUpload.aspx.cs" Inherits="ContextMenu.GridFileUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdFileUpload" runat="server" AutoGenerateColumns="false" ShowFooter="true" EmptyDataText="No records found">
            <Columns>              
                <asp:TemplateField HeaderText="Student-ID">
                    <ItemTemplate>
                        <asp:Label ID="lblStudentID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Studentid") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtStudentID" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Photo">
                <ItemTemplate>
                        <asp:Image ID="imgPhoto" runat="server" Width="100px" Height="120px" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "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>
        </asp:GridView>
        <asp:Label ID="lblMsg" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


C# Code (code behind ) :

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

namespace ContextMenu
{
    public partial class GridFileUpload : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection("Data Source=MUNESH;Initial Catalog=GridData;Integrated Security=True");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        protected void BindGrid()
        {
            DataSet ds = new DataSet();
            DataTable dtData = new DataTable();
            conn.Open();
            string cmdstr = "Select * from FileUpload";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);
            cmd.ExecuteNonQuery();
            dtData = ds.Tables[0];

            if (dtData.Rows.Count > 0)
            {
                grdFileUpload.DataSource = dtData;
                grdFileUpload.DataBind();
            }
            else
            {
                dtData.Rows.Add(dtData.NewRow());
                grdFileUpload.DataSource = dtData;
                grdFileUpload.DataBind();
                int TotalColumns = grdFileUpload.Rows[0].Cells.Count;
                grdFileUpload.Rows[0].Cells.Clear();
                grdFileUpload.Rows[0].Cells.Add(new TableCell());
                grdFileUpload.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                grdFileUpload.Rows[0].Cells[0].Text = "No records Found";
            }
            ds.Dispose();
            conn.Close();

        }

        protected void btnUpload_OnClick(object sender, EventArgs e)
        {
            TextBox txtStudentID = (TextBox)grdFileUpload.FooterRow.FindControl("txtStudentID");
            TextBox txtName = (TextBox)grdFileUpload.FooterRow.FindControl("txtName");
            FileUpload fuploadFile = (FileUpload)grdFileUpload.FooterRow.FindControl("fUpload");
            Button btnUpload = (Button)grdFileUpload.FooterRow.FindControl("btnUpload");

            if (fuploadFile.HasFile)
            {
                string fileName = fuploadFile.FileName;
                string exten = Path.GetExtension(fileName);

                //check that the file is of the permitted file type               

                exten = exten.ToLower();

                string[] FileTypes = new string[4];

                FileTypes[0] = ".jpg";
                FileTypes[1] = ".jpeg";
                FileTypes[2] = ".gif";
                FileTypes[3] = ".png";

                bool IsFileTypeCorrect = false;

                for (int i = 0; i <= 3; i++)
                {
                    if (exten == FileTypes[i])
                    {

                        IsFileTypeCorrect = true;
                    }
                }

                if (!IsFileTypeCorrect)
                {
                    lblMsg.Text = "File Type is not in a correct formate";
                }
                else
                {
                    //upload the file onto the server
                    fuploadFile.SaveAs(Server.MapPath("~/Images/" + fileName));

                    conn.Open();
                    string cmdstr = "insert into FileUpload(Studentid,name,photo) values(@Studentid,@name,@photo)";
                    SqlCommand cmd = new SqlCommand(cmdstr, conn);
                    cmd.Parameters.AddWithValue("@Studentid", txtStudentID.Text);
                    cmd.Parameters.AddWithValue("@name", txtName.Text);
                    cmd.Parameters.AddWithValue("@photo", "Images/" + fileName);
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    BindGrid();
                }
            }

        }
    }
}

 Output Will be like following


No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...