Upload Image to server with autogenrated Name based on Employee code using C# and VB.Net in ASP.Net

Last Reply on Feb 27, 2017 06:46 AM By Indresh

Posted on Feb 16, 2017 11:21 PM

Hiiii,

I want to upload images on server location (example.128.9.26.11\Images) with the auto generated unique names like if EmployeeCode is 2490 then the image name should be 00002490 .It means the name length is 8 char.if emp number is 100 then it should be 00000100.After that i want to perform update and delete operation on it.

While uploading that uploaded images should be display in picture box.

And also want to display that images in gridview.

Posted on Feb 17, 2017 01:49 AM

Hi Waghmare,

I have created sample code which fulfill your requirement.

HTML

<div>
    <asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvEmployees_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="EmployeeId">
                <ItemTemplate>
                    <asp:Label ID="LblEmployeeId" runat="server" Text='<%#Eval("EmployeeId")%>' />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:Label ID="LblEmployeeIdEdit" runat="server" Text='<%#Eval("EmployeeId")%>' />
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="EmployeeName" HeaderText="EmployeeName" />
            <asp:TemplateField HeaderText="Pics">
                <ItemTemplate>
                    <asp:Image ID="empimage" Height="50px" runat="server" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:FileUpload ID="FileUpload1Edit" runat="server" />
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="btnEdit" Text="Edit" OnClick="OnEdit" runat="server" />
                    <asp:LinkButton ID="btnDelete" Text="Delete" OnClick="OnDelete" runat="server" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:LinkButton Text="Update" OnClick="OnUpdate" runat="server" />
                    <asp:LinkButton Text="Cancel" OnClick="OnCancel" runat="server" />
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

C#

private string constring = ConfigurationManager.ConnectionStrings["constr"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        GetData();
    }
}

protected void GetData()
{
    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeTest", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gvEmployees.DataSource = dt;
    gvEmployees.DataBind();
}

protected void OnEdit(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    gvEmployees.EditIndex = row.RowIndex;
    GetData();
}

protected void OnUpdate(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    string EmployeeId = (row.FindControl("LblEmployeeIdEdit") as Label).Text;
    string sourcefile = ((row.FindControl("FileUpload1Edit") as FileUpload).PostedFile.FileName);
    string directoryPath = Server.MapPath("~/Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length) + EmployeeId + ".jpg");
    if (File.Exists(directoryPath) && sourcefile != null)
    {
        File.Delete(directoryPath);
        string newFile = Server.MapPath("Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length) + EmployeeId + ".jpg");
        (row.FindControl("FileUpload1Edit") as FileUpload).SaveAs(newFile);
    }

    gvEmployees.EditIndex = -1;
    GetData();
}

protected void OnDelete(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand("DELETE FROM EmployeeTest WHERE EmployeeId=@EmployeeId", con);
    string EmployeeId = (row.FindControl("LblEmployeeId") as Label).Text;
    cmd.Parameters.AddWithValue("@EmployeeId", EmployeeId);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    GetData();
}

protected void OnCancel(object sender, EventArgs e)
{
    gvEmployees.EditIndex = -1;
    GetData();
}

protected void gvEmployees_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
    {
        string EmployeeId = (e.Row.FindControl("LblEmployeeId") as Label).Text;

        (e.Row.FindControl("empimage") as Image).ImageUrl = "~/Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length) + EmployeeId + ".jpg";
    }
}

Vb.net

Private constring As String = ConfigurationManager.ConnectionStrings("constr").ToString()
Protected Sub Page_Load(sender As Object, e As EventArgs)
	If Not Me.IsPostBack Then
		GetData()
	End If
End Sub

Protected Sub GetData()
	Dim con As New SqlConnection(constring)
	Dim cmd As New SqlCommand("SELECT * FROM EmployeeTest", con)
	Dim sda As New SqlDataAdapter(cmd)
	Dim dt As New DataTable()
	sda.Fill(dt)
	gvEmployees.DataSource = dt
	gvEmployees.DataBind()
End Sub

Protected Sub OnEdit(sender As Object, e As EventArgs)
	Dim row As GridViewRow = TryCast(TryCast(sender, LinkButton).NamingContainer, GridViewRow)
	gvEmployees.EditIndex = row.RowIndex
	GetData()
End Sub

Protected Sub OnUpdate(sender As Object, e As EventArgs)
	Dim row As GridViewRow = TryCast(TryCast(sender, LinkButton).NamingContainer, GridViewRow)
	Dim EmployeeId As String = TryCast(row.FindControl("LblEmployeeIdEdit"), Label).Text
	Dim sourcefile As String = (TryCast(row.FindControl("FileUpload1Edit"), FileUpload).PostedFile.FileName)
	Dim directoryPath As String = Server.MapPath((Convert.ToString("~/Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length)) & EmployeeId) + ".jpg")
	If File.Exists(directoryPath) AndAlso sourcefile IsNot Nothing Then
		File.Delete(directoryPath)
		Dim newFile As String = Server.MapPath((Convert.ToString("Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length)) & EmployeeId) + ".jpg")
		TryCast(row.FindControl("FileUpload1Edit"), FileUpload).SaveAs(newFile)
	End If

	gvEmployees.EditIndex = -1
	GetData()
End Sub

Protected Sub OnDelete(sender As Object, e As EventArgs)
	Dim row As GridViewRow = TryCast(TryCast(sender, LinkButton).NamingContainer, GridViewRow)
	Dim con As New SqlConnection(constring)
	Dim cmd As New SqlCommand("DELETE FROM EmployeeTest WHERE EmployeeId=@EmployeeId", con)
	Dim EmployeeId As String = TryCast(row.FindControl("LblEmployeeId"), Label).Text
	cmd.Parameters.AddWithValue("@EmployeeId", EmployeeId)
	con.Open()
	cmd.ExecuteNonQuery()
	con.Close()
	GetData()
End Sub

Protected Sub OnCancel(sender As Object, e As EventArgs)
	gvEmployees.EditIndex = -1
	GetData()
End Sub

Protected Sub gvEmployees_RowDataBound(sender As Object, e As GridViewRowEventArgs)
	If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate) Then
		Dim EmployeeId As String = TryCast(e.Row.FindControl("LblEmployeeId"), Label).Text

		TryCast(e.Row.FindControl("empimage"), Image).ImageUrl = (Convert.ToString("~/Files/" + "00000000".Substring(EmployeeId.Length, 8 - EmployeeId.Length)) & EmployeeId) + ".jpg"
	End If
End Sub

Screenshot