How to use Fileupload control in Gridview in Asp.net


Introduction: In this post I try to explain how we can use the Fileupload control in Gridview.

Description:
I have created a table LINQ_TABLE

Add new webform to project. Add the Connectionstring in web.config file of website.

<configuration>
       <connectionStrings>
    <add name="con" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

Drag and drop Gridview Data control from Toolbox.
<asp:GridView ID="grduser" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            onrowediting="GridView1_RowEditing"
            onrowcancelingedit="grduser_RowCancelingEdit"
            onrowupdating="grduser_RowUpdating" onrowdeleting="grduser_RowDeleting"
            AllowPaging="True" onpageindexchanging="grduser_PageIndexChanging"
            PageSize="8">
            <Columns>
                <asp:TemplateField HeaderText="Username">
                   
                    <ItemTemplate>
                        <asp:Label ID="lbluser" runat="server" Text='<%# Eval("USERNAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="First Name">
                  
                    <ItemTemplate>
                        <asp:Label ID="lblfirst" runat="server" Text='<%# Eval("FIRST_NAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                  
                    <ItemTemplate>
                        <asp:Label ID="lbllast" runat="server" Text='<%# Eval("LAST_NAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Date Of Birth">
                   
                    <ItemTemplate>
                        <asp:Label ID="lblbirth" runat="server" Text='<%# Eval("DATE_BIRTH") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Sex">
                  
                    <ItemTemplate>
                        <asp:Label ID="lblsex" runat="server" Text='<%# Eval("SEX") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Age">
                   
                    <ItemTemplate>
                        <asp:Label ID="lblage" runat="server" Text='<%# Eval("AGE") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Profile Image">
                <EditItemTemplate>
                  <asp:FileUpload ID="FileUpload1" runat="server" />
                </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("IMAGE") %>' Height="150px" Width="150px"/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
            <PagerSettings PageButtonCount="8" />
        </asp:GridView>

Now go to .aspx.cs page.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (!IsPostBack)
        {
            bindgrid();
        }
    }
    private void bindgrid()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from LINQ_TABLE", con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
       if (dt.Rows.Count > 0)
            {
                grduser.DataSource = dt;
                grduser.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                grduser.DataSource = dt;
                grduser.DataBind();
                int columncount = grduser.Rows[0].Cells.Count;
                grduser.Rows[0].Cells.Clear();
                grduser.Rows[0].Cells.Add(new TableCell());
                grduser.Rows[0].Cells[0].ColumnSpan = columncount;
                grduser.Rows[0].Cells[0].Text = "No Records Available";
            }

    }
    protected void grduser_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {


            int ID = Convert.ToInt32(grduser.DataKeys[e.RowIndex].Values["ID"].ToString());
            FileUpload flimage = (FileUpload)grduser.Rows[e.RowIndex].FindControl("FileUpload1");
            string image = Server.MapPath("~/img/") + Guid.NewGuid() + flimage.PostedFile.FileName;
            flimage.PostedFile.SaveAs(image);
            string fl = image.Substring(image.LastIndexOf("\\"));
            string[] split = fl.Split('\\');
            string newpath = split[1];
            string imagepath = "~/img/" + newpath;
            SqlCommand cmd = new SqlCommand("Update LINQ_TABLE set IMAGE= @IMAGE where ID=" + ID, con);
            cmd.Parameters.AddWithValue("@IMAGE", imagepath);
            cmd.ExecuteNonQuery();
            grduser.EditIndex = -1;
            bindgrid();
        }
        catch (Exception ex)
        {
        }
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grduser.EditIndex = e.NewEditIndex;
        bindgrid();
    }
    protected void grduser_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int ID = Convert.ToInt32(grduser.DataKeys[e.RowIndex].Value.ToString());
            SqlCommand cmd = new SqlCommand("delete from LINQ_TABLE where ID=" + ID, con);
            //con.Open();
            cmd.ExecuteNonQuery();
            bindgrid();
        }
        catch (Exception ex)
        {
        }
    }
    protected void grduser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grduser.EditIndex = -1;
        bindgrid();
    }
    protected void grduser_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grduser.PageIndex = e.NewPageIndex;
        bindgrid();
    }

In VB

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        If Not IsPostBack Then
            bindgrid()
        End If
    End Sub
    Private Sub bindgrid()
        Dim adp As New SqlDataAdapter("select * from LINQ_TABLE", con)
        Dim dt As New DataTable()
        adp.Fill(dt)
        If dt.Rows.Count > 0 Then
            grduser.DataSource = dt
            grduser.DataBind()
        Else
            dt.Rows.Add(dt.NewRow())
            grduser.DataSource = dt
            grduser.DataBind()
            Dim columncount As Integer = grduser.Rows(0).Cells.Count
            grduser.Rows(0).Cells.Clear()
            grduser.Rows(0).Cells.Add(New TableCell())
            grduser.Rows(0).Cells(0).ColumnSpan = columncount
            grduser.Rows(0).Cells(0).Text = "No Records Available"
        End If

    End Sub
    Protected Sub grduser_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        Try
                       Dim ID As Integer = Convert.ToInt32(grduser.DataKeys(e.RowIndex).Values("ID").ToString())
            Dim flimage As FileUpload = DirectCast(grduser.Rows(e.RowIndex).FindControl("FileUpload1"), FileUpload)
Dim image As String = (Server.MapPath("~/img/") & Convert.ToString(Guid.NewGuid()) & flimage.PostedFile.FileName)
            flimage.PostedFile.SaveAs(image)
            Dim fl As String = image.Substring(image.LastIndexOf("\"))
            Dim split As String() = fl.Split("\"c)
            Dim newpath As String = split(1)
            Dim imagepath As String = "~/img/" & newpath
            Dim cmd As New SqlCommand("Update LINQ_TABLE set IMAGE= @IMAGE where ID=" & ID, con)
            cmd.Parameters.AddWithValue("@IMAGE", imagepath)
            cmd.ExecuteNonQuery()
            grduser.EditIndex = -1
            bindgrid()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        grduser.EditIndex = e.NewEditIndex
        bindgrid()
    End Sub
    Protected Sub grduser_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Try
            Dim ID As Integer = Convert.ToInt32(grduser.DataKeys(e.RowIndex).Value.ToString())
            Dim cmd As New SqlCommand("delete from LINQ_TABLE where ID=" & ID, con)
            'con.Open();
            cmd.ExecuteNonQuery()
            bindgrid()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grduser_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        grduser.EditIndex = -1
        bindgrid()
    End Sub
    Protected Sub grduser_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        grduser.PageIndex = e.NewPageIndex
        bindgrid()
    End Sub

Now run and check the result.

Related Articles on Gridview:

Ø  How to bind Gridview using Sqldataadapter, Datatable andQuery in Asp.net

Ø  How to highlight row on mouse hover in Gridview

Ø  How to edit and update Dropdownlist in Gridview datacontrol in Asp.net

Ø  How to Search Records in Gridview in Asp.net

Ø  How to Bind Gridview using Store Procedure, SqlDataAdapterand Datatable in Asp.net

Ø  How to use RadioButtonList control inside the Gridview inAsp.net

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget