Retain (Keep) previous uploaded FileName if TextBox vale is Empty using C# and VB.Net in ASP.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

Hey

I am trying to edit my records which is functioning very well but when I dont upload any image on editing and click on update button then image name is set as null because nothing is being uploaded.

But it old image name should be as it is if nothing is being uploaded

thanks

    public partial class SP_edit_new : System.Web.UI.Page
    {
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            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;
                FileUpload1.SaveAs(MapPath(path));
                UpdateFile(path);
                ClearControls();
            }
            else
            {
                path = Image1.ImageUrl;
               
                UpdateFile(path);
                FillGrid();
            }
            FillGrid();
            lblMessage.Text = "Updated Successfully.";
        }

        private void UpdateFile(string path)
        {

            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            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);
            string constr = ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand("UPDATE SP_Afterlogin2 SET Images =@Path,Bussiness_name=@Bussiness_name,city=@city,Image_name=@Image_name,name=@name,toll_free=@toll_free,website_link=@website_link,payment_mode=@payment_mode,email=@email,address=@address,h_open=@h_open WHERE Id =@Id", con);
            cmd.Parameters.AddWithValue("@Id", Id.Value);
            cmd.Parameters.AddWithValue("@Path", path);
            cmd.Parameters.AddWithValue("@Bussiness_name", DropDownList1.SelectedValue.ToString());
            cmd.Parameters.AddWithValue("@city", DropDownList2.SelectedValue.ToString());
            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("@Image_name",fileName);
            cmd.Parameters.AddWithValue("@address", txt_Address.Text);
            cmd.Parameters.AddWithValue("@h_open", open2);
            con.Open();
            cmd.ExecuteNonQuery();
            con.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
    {
        fileName = txt_img.Text;
        path = Image1.ImageUrl;
    }
    UpdateFile(path, fileName);
    ClearControls();
    BindGrid();
    lblMessage.Text = "Updated Successfully.";
}

private void UpdateFile(string path, string fileName)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("UPDATE tblFilesPath SET Path =@Path , Name = @FileName WHERE Id =@Id", con);
    cmd.Parameters.AddWithValue("@Id", Id.Value);
    cmd.Parameters.AddWithValue("@Path", path);
    cmd.Parameters.AddWithValue("@FileName", fileName);
    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
            fileName = txt_img.Text
            path = Image1.ImageUrl
        End If

        UpdateFile(path, fileName)
        ClearControls()
        BindGrid()
        lblMessage.Text = "Updated Successfully."
    End Sub

    Private Sub UpdateFile(ByVal path As String, ByVal fileName 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 , Name = @FileName WHERE Id =@Id", con)
        cmd.Parameters.AddWithValue("@Id", Id.Value)
        cmd.Parameters.AddWithValue("@Path", path)
        cmd.Parameters.AddWithValue("@FileName", fileName)
        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