This
article is the 2nd part of create photo album application. In this
part I am going to explain how to upload or add photo to album in asp.net
In
the first part I have explained how to create photo album in asp.net.
Description:
After
created the album we will be redirected to upload/add photo page. On this page
we will upload the image and uploaded image will be displayed below (in
gridview) to enter description and click the save button to save the changes.
Implementation:
Create
store procedure to save/insert the uploaded photo and get the id of last
inserted record
Create PROCEDURE
Sp_InsertPhoto
(
@albumid int,
@photopath varchar(max),
@id int output
)
AS
BEGIN
            SET
NOCOUNT ON;
    Insert
into Tb_Photo (AlbumId,PhotoPath) values (@albumid,@photopath)
set @id = SCOPE_IDENTITY()  
return @id  
END
Store
procedure to get the data
Create PROCEDURE
Sp_GetPhotoData
(
@id int
)
AS
BEGIN
            SET
NOCOUNT ON;
Select * from dbo.Tb_Photo where photoid = @id
END
Store
procedure to update the information/description
Create PROCEDURE
Sp_UpdatePhoto
(
@id int,
@PhotoName varchar(100)
)
AS
BEGIN
            SET
NOCOUNT ON;
    Update
Tb_Photo set PhotoName=@PhotoName
where PhotoID=@id
END
HTML Markup
of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin-left:50px"> 
   <table>
    <tr> <td><asp:Button ID="btngallery"
runat="server"
Text="View
Album" 
                 /></td><td>
                 <asp:Button ID="btncreate" runat="server" Text="Create Album" 
                      /></td> </tr>
                        <tr><td></td><td></td></tr>
                      <tr><td></td><td></td></tr>
                       <tr><td></td><td></td></tr>
   </table>
     <table style="margin-top:30px">   
     <tr><td>Upload Image
to Album :</td><td> <asp:FileUpload ID="FileUpload1" runat="server" />
        </td></tr>
            <tr><td></td><td></td></tr>
            <tr><td></td><td><asp:Button ID="Button1" runat="server"
            Text="Upload image" onclick="Button1_Click" /></td></tr>
            <tr><td></td><td></td></tr>
     </table>
     <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>    
    <asp:UpdatePanel ID="updatepanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>   
        <asp:GridView ID="grdphoto" runat="server" AutoGenerateColumns="false" DataKeyNames="PhotoID">
        <Columns>
       <asp:TemplateField>
                <ItemTemplate>
                <table>
                <tr>
                <td>
                    <asp:Image ID="Image3" runat="server" ImageUrl='<%# Eval("PhotoPath","~/img/{0}") %>' Height="300px" Width="300px" /></td>                   
                </tr>
                </table>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                <ItemTemplate>
                 <table>
                 <tr><td>Enter
Description :</td></tr>
                 <tr>
                    <td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr>
                    </table> 
                </ItemTemplate>
                </asp:TemplateField>
        </Columns>
        </asp:GridView>
        </ContentTemplate>  
</asp:UpdatePanel>
         <table><tr><td><asp:Button ID="btnsave" runat="server" Text="Save" /></td></tr></table>
        <br />
        <br />
    </div>
    </form>
</body>
</html>
Add the
namespace
C#
Code:
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
VB.net
Code:
Imports
System.Configuration
Imports
System.Data.SqlClient
Imports
System.Data
Create
sqlconnection and set visibility false of save button on page load.
C#
Code:
SqlConnection
con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    int id;
protected void Page_Load(object
sender, EventArgs e)
    {       
        btnsave.Visible = false;
    }  
VB.net
Code:
Private
con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Private id As Integer
  Protected Sub Page_Load(sender As
Object, e As
System.EventArgs) Handles
Me.Load
        btnsave.Visible = False
    End Sub
Inserting
the record and show uploaded image in gridview
Save
the uploaded image to folder and insert the path into database. On button click
write the below given code:
C#
Code:
protected void Button1_Click(object
sender, EventArgs e)
    {
        string
filepath = Server.MapPath("~/img/")
+ Guid.NewGuid() +
FileUpload1.PostedFile.FileName;
        FileUpload1.SaveAs(filepath);
        string
fl = filepath.Substring(filepath.LastIndexOf("\\"));
        string[]
split = fl.Split('\\');
        string
newpath = split[1];
        string
imagepath = "~/img/" + newpath;
        con.Open();
        SqlCommand
cmd = new SqlCommand("Sp_InsertPhoto", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@albumid", Convert.ToInt32(Session["albumid"].ToString()));
        cmd.Parameters.AddWithValue("@photopath", newpath);
        cmd.Parameters.Add("@id", SqlDbType.Int);
        cmd.Parameters["@id"].Direction
= ParameterDirection.Output;
        cmd.ExecuteNonQuery();
        id = (int)cmd.Parameters["@id"].Value;
        BindGrid();
    }
VB.net
Code:
Protected Sub Button1_Click(sender As
Object, e As
System.EventArgs) Handles
Button1.Click
        Dim
filepath As String
= Server.MapPath("~/img/") + Guid.NewGuid().ToString() +
FileUpload1.PostedFile.FileName
        FileUpload1.SaveAs(filepath)
        Dim fl As String =
filepath.Substring(filepath.LastIndexOf("\"))
        Dim
split As String()
= fl.Split("\"c)
        Dim
newpath As String
= split(1)
        Dim
imagepath As String
= Convert.ToString("~/img/")
& newpath
        con.Open()
        Dim cmd
As New SqlCommand("Sp_InsertPhoto",
con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@albumid", Convert.ToInt32(Session("albumid").ToString()))
        cmd.Parameters.AddWithValue("@photopath", newpath)
        cmd.Parameters.Add("@id", SqlDbType.Int)
        cmd.Parameters("@id").Direction
= ParameterDirection.Output
        cmd.ExecuteNonQuery()
        id = CInt(cmd.Parameters("@id").Value)
        BindGrid()
    End Sub
Bind the
Gridview
Create
a method to get the last inserted record from database to enter description
C#
Code:
public void BindGrid()
    {
        SqlDataAdapter
adp = new SqlDataAdapter("Sp_GetPhotoData", con);
        adp.SelectCommand.CommandType = CommandType.StoredProcedure;
       
adp.SelectCommand.Parameters.AddWithValue("@id",
id);
        DataTable
dt = new DataTable();
        adp.Fill(dt);
        grdphoto.DataSource = dt;
        grdphoto.DataBind();     
        btnsave.Visible = true;
    }
VB.net
Code:
Public Sub BindGrid()
        Dim adp
As New SqlDataAdapter("Sp_GetPhotoData",
con)
        adp.SelectCommand.CommandType = CommandType.StoredProcedure
       
adp.SelectCommand.Parameters.AddWithValue("@id",
id)
        Dim dt As New DataTable()
        adp.Fill(dt)
        grdphoto.DataSource = dt
        grdphoto.DataBind()
        btnsave.Visible = True
    End Sub
Updating the
data
Enter
the description for image and write the below given code on save button click:
C#
Code:
protected void btnsave_Click1(object
sender, EventArgs e)
    {
        foreach
(GridViewRow gvrow in
grdphoto.Rows)
        {
            int
id = Convert.ToInt32(grdphoto.DataKeys[gvrow.RowIndex].Value.ToString());
            string
name = ((TextBox)gvrow.FindControl("TextBox1")).Text;
            SqlCommand
cmd = new SqlCommand("Sp_UpdatePhoto", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@PhotoName", name);
            cmd.Parameters.AddWithValue("@id", id);
            cmd.ExecuteNonQuery();
            con.Close();
            grdphoto.DataSource = null;
            grdphoto.DataBind();
        }
     }
VB.net
Code:
Protected Sub btnsave_Click(sender As
Object, e As
System.EventArgs) Handles
btnsave.Click
        For Each gvrow As GridViewRow In
grdphoto.Rows
            Dim
id As Integer =
Convert.ToInt32(grdphoto.DataKeys(gvrow.RowIndex).Value.ToString())
            Dim
name As String
= DirectCast(gvrow.FindControl("TextBox1"), TextBox).Text
            Dim
cmd As New SqlCommand("Sp_UpdatePhoto",
con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@PhotoName", name)
            cmd.Parameters.AddWithValue("@id", id)
            cmd.ExecuteNonQuery()
            con.Close()
            grdphoto.DataSource = Nothing
            grdphoto.DataBind()
        Next
    End Sub
Redirect
to Create new album and view gallery
C#
Code:
protected void btngallery_Click(object
sender, EventArgs e)
    {
        Response.Redirect("gallery.aspx");
    }
    protected void btncreate_Click(object
sender, EventArgs e)
    {
        Response.Redirect("frmAlbum.aspx");
    }
VB.net
Code:
Protected Sub btngallery_Click(sender As
Object, e As
System.EventArgs) Handles
btngallery.Click
        Response.Redirect("gallery.aspx")
    End Sub
    Protected Sub btncreate_Click(sender As
Object, e As
System.EventArgs) Handles
btncreate.Click
        Response.Redirect("frmalbumvb.aspx")
    End Sub
Build
and run the application. 
<< How to create photo album in asp.net _ Part I
 
 
.png) 

No comments:
Post a Comment