Retain (Keep) previous uploaded Image if no file selected in ASP.Net FileUpload control using C# and VB.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

Hey

I am trying to show image in a table in an image control but image in not showing then i want to update the image it is working fine if i choose an image everytime before clicking on update button otherwise it is taking null value.

I want to show old image if not selected any image .

please help.

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                GridViewRow grow = btn.NamingContainer as GridViewRow;
                string path = "~/uploads/";
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                if (FileUpload1.HasFile)
                {
                    path += FileUpload1.FileName;
                    //save image in folder    
                    FileUpload1.SaveAs(MapPath(path));
                }
                else
                {
                    // use previous user image if new image is not changed
                    Image img = (Image)(grow.FindControl("img_user") as Image);
                    path = img.ImageUrl;

                }
                List<String> open = new List<String>();
                if (ddlTimeFrom.SelectedIndex > 0 && ddlTimeTo.SelectedIndex > 0)
                {
                    open.Add(ddlTimeFrom.Text);
                    open.Add(ddlTimeTo.Text);
                }
                string open2 = string.Join(", ", open);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "update SP_Afterlogin2 set Bussiness_name=@Bussiness_name,city=@city,name=@name,toll_free=@toll_free,website_link=@website_link,payment_mode=@payment_mode,email=@email,Images=@Images,Image_name=@Image_name,address=@address,h_open=@h_open where Id=@Id";
                cmd.Parameters.AddWithValue("@Id", Id.Value);
                cmd.Parameters.AddWithValue("@Bussiness_name", txt_Bname.Text);
                cmd.Parameters.AddWithValue("@city", txt_city.Text);
                cmd.Parameters.AddWithValue("@name", txt_name.Text);
                cmd.Parameters.AddWithValue("@toll_free", txt_toll.Text);
                cmd.Parameters.AddWithValue("@website_link", txt_link.Text);
                cmd.Parameters.AddWithValue("@payment_mode", txt_pay.Text);
                cmd.Parameters.AddWithValue("@email", txt_email.Text);
                cmd.Parameters.AddWithValue("@Images",path);
                cmd.Parameters.AddWithValue("@Image_name", fileName);
                cmd.Parameters.AddWithValue("@address", txt_Address.Text);
                cmd.Parameters.AddWithValue("@h_open", open2);
                
                cmd.Connection = mycon;
                mycon.Open();
                cmd.ExecuteNonQuery();
                mycon.Close();
                FillGrid();
                ClearControls();
                lblMessage.Text = "Updated Successfully.";
            }
            catch(Exception ex)
            {
                Response.Write(ex);
            }
            finally
            {
                if (mycon.State == ConnectionState.Open)
                    mycon.Close();
            }
        }

 

Posted 2 months ago Modified on 2 months ago

Hi itsme,

Refer below sample.

HTML

<div style="scrollbar-highlight-color: aqua" onscroll="true">
    <table align="center" style="position: relative; top: 20px;">
        <tr>
            <td>
                <table align="center">
                    <tr>
                        <td>
                            Image Name :
                        </td>
                        <td>
                            <asp:TextBox ID="txt_img" runat="server" MaxLength="200" Width="250px"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Image :
                        </td>
                        <td>
                            <asp:Image ID="Image1" runat="server" Height="80px" Width="100px" />
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center">
                            <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
                            <asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" />
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align="center">
                <br />
                <asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="Blue"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="gvDepartments" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True"
                    EmptyDataText="No Records Found" GridLines="both" CssClass="gv" EmptyDataRowStyle-ForeColor="Red">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblId" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText=" Hours of Open">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Image">
                            <ItemTemplate>
                                <asp:Image ID="img" runat="server" ImageUrl='<%# Eval("Path") %>' Height="80px" Width="100px" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Action">
                            <ItemTemplate>
                                <asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" />
                                <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure? want to delete the department.');" />
                                <asp:Label ID="Id" runat="server" Text='<%#Eval("Id") %>' Visible="false"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>
    <input type="hidden" runat="server" id="Id" />
</div>

Namespaces

C#

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

VB.Net

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

Code

C#

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

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("SELECT Id, Name, Path FROM tblFilesPath", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    gvDepartments.DataSource = dt;
    gvDepartments.DataBind();
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    string path = "~/uploads/";
    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    if (FileUpload1.HasFile)
    {
        path += FileUpload1.FileName;
        FileUpload1.SaveAs(MapPath(path));       
    }
    else
    {
        path = Image1.ImageUrl;
    }
    UpdateFile(path);
    BindGrid();
    ClearControls();
    lblMessage.Text = "Updated Successfully.";
}

private void UpdateFile(string path)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("UPDATE tblFilesPath SET Path =@Path WHERE Id =@Id", con);
    cmd.Parameters.AddWithValue("@Id", Id.Value);
    cmd.Parameters.AddWithValue("@Path", path);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

private void ClearControls()
{
    txt_img.Text = "";
    Image1.ImageUrl = "";
}

protected void btnClear_Click(object sender, EventArgs e)
{
    ClearControls();
}

protected void btnEdit_Click(object sender, EventArgs e)
{
    try
    {
        Button btn = sender as Button;
        GridViewRow grow = btn.NamingContainer as GridViewRow;
        Id.Value = (grow.FindControl("Id") as Label).Text;
        txt_img.Text = (grow.FindControl("lblName") as Label).Text;
        Image img = (grow.FindControl("img") as Image);
        Image1.ImageUrl = img.ImageUrl;
        btnUpdate.Visible = true;
    }
    catch
    {

    }
}

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handle Me.Load
        If Not Me.IsPostBack Then
            BindGrid()
        End If
    End Sub

    Private Sub BindGrid()
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim con As SqlConnection = New SqlConnection(constr)
        Dim cmd As SqlCommand = New SqlCommand("SELECT Id, Name, Path FROM tblFilesPath", con)
        Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
        Dim dt As DataTable = New DataTable()
        da.Fill(dt)
        gvDepartments.DataSource = dt
        gvDepartments.DataBind()
    End Sub
    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim path As String = "~/uploads/"
        Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
        If FileUpload1.HasFile Then
            path += FileUpload1.FileName
            FileUpload1.SaveAs(MapPath(path))
        Else
            path = Image1.ImageUrl
        End If
        UpdateFile(path)
        BindGrid()
        ClearControls()
        lblMessage.Text = "Updated Successfully."
    End Sub
    Private Sub UpdateFile(ByVal path As String)
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim con As SqlConnection = New SqlConnection(constr)
        Dim cmd As SqlCommand = New SqlCommand("UPDATE tblFilesPath SET Path =@Path WHERE Id =@Id", con)
        cmd.Parameters.AddWithValue("@Id", Id.Value)
        cmd.Parameters.AddWithValue("@Path", path)
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Sub

    Private Sub ClearControls()
        txt_img.Text = ""
        Image1.ImageUrl = ""
    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs)
        ClearControls()
    End Sub

    Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim btn As Button = TryCast(sender, Button)
            Dim grow As GridViewRow = TryCast(btn.NamingContainer, GridViewRow)
            Id.Value = (TryCast(grow.FindControl("Id"), Label)).Text
            txt_img.Text = (TryCast(grow.FindControl("lblName"), Label)).Text
            Dim img As Image = (TryCast(grow.FindControl("img"), Image))
            Image1.ImageUrl = img.ImageUrl
            btnUpdate.Visible = True
        Catch
        End Try
    End Sub

Screenshot