[ ASP .net C# jQuery SQL Server Database ] Dynamic Image Gallery

Create Folder: ‘SlideImages’ and share/ make permission

Create Database Table:

SlideShowImage([Id]
,[ImageName]
,[ImagePath]
,[Description])

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajaxToolkit” %>

<script src=”swissarmy.js” type=”text/javascript”>
</script>

Download: swissarmy.js and add to project

Client Side .aspx

<div align=”center” style=”width: 480px;”>
<p>
<script type=”text/javascript”>
//Notes on Parameters: The only required parameter is the slides_array_name. If Width is used, so must Height.
//Interval is optional too. It is always last, either fourth after Width and Height or second after Slides_array_name.
//Usage: new inter_slide(Slides_array_name, Width, Height, Interval)
new inter_slide(slides)
</script>
</p>
</div>

Client Side .cs

public void DynamicSlideShow()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“SelfAssessmentConnStr”].ConnectionString);

con.Open();
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand(“SELECT ImageName,Description from SlideShowImage”, con);// SlideShowTable
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);

String LoadSlideShow = “<script type=’text/javascript’>” +
“var preload_ctrl_images = true;” +
“var previmg = ‘left.gif’;” +
“var stopimg = ‘stop.gif’;” +
“var playimg = ‘play.gif’;” +
“var nextimg = ‘right.gif’;” +
“var slides = []; “;

for (Int32 i = 0; i < dt.Rows.Count; i++)
{
LoadSlideShow = LoadSlideShow + “slides[” + i.ToString() + “] = [‘SlideImages/” + dt.Rows[i][0].ToString() + “‘, ‘” + dt.Rows[i][1].ToString() + “‘];”;
}
LoadSlideShow = LoadSlideShow + “</script>”;

con.Close();
Page.ClientScript.RegisterClientScriptBlock(typeof(object), “JavaScriptBlock”, LoadSlideShow.ToString());
}

Admin Side .aspx

<%@ Register TagPrefix=”asp” Namespace=”AjaxControlToolkit” Assembly=”AjaxControlToolkit” %>
<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>
<link rel=”stylesheet” href=”lightbox.css” type=”text/css” media=”screen” />
<script type=”text/javascript” src=”prototype.js”></script>
<script type=”text/javascript” src=”scriptaculous.js?load=effects”></script>
<script type=”text/javascript” src=”lightbox.js”></script>

 

<div id=”divImageGallery” runat=”server” align=”center”>
<br />
<div align=”center” style=”font-family: Arial Black; font-size: 20px; font-weight: bold;”>
Home Image Gallery Setup
</div>
<br />
<div>
<table align=”center”>
<tr>
<td>
Select Image:
</td>
<td>
<asp:FileUpload ID=”fileuploadimages” runat=”server” />
</td>
</tr>
<tr>
<td valign=”top”>
Image Description:
</td>
<td>
<asp:TextBox ID=”txtDesc” SkinID=”TextAreaPhotoGallery” runat=”server” TextMode=”MultiLine”></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td align=”right”>
<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnSubmit_Click” />
</td>
</tr>
<tr>
<td colspan=”2″>
<asp:DataList ID=”dlImages” runat=”server” RepeatColumns=”3″ CellPadding=”5″>
<ItemTemplate>
<a id=”imageLink” href='<%# Eval(“ImageName”,”~/SlideImages/{0}”) %>’ title='<%#Eval(“Description”) %>’
rel=”lightbox[Brussels]” runat=”server”>
<asp:Image ID=”Image1″ ImageUrl='<%# Bind(“ImageName”, “~/SlideImages/{0}”) %>’ runat=”server”
Width=”115″ Height=”85″ />
</a>
</ItemTemplate>
<ItemStyle BorderColor=”Chocolate” BorderStyle=”Solid” BorderWidth=”3px” HorizontalAlign=”Center”
VerticalAlign=”Bottom” />
</asp:DataList>
</td>
</tr>
</table>
<br />
</div>
<br />
<div align=”center”>
<div>
<asp:Label ID=”lblImageMessage” runat=”server” ForeColor=”Red” />
</div>
<div style=”width: 700px;”>
<asp:GridView ID=”gvSlideEdit” AutoGenerateColumns=”False” EmptyDataText=”No data available.”
runat=”server” BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
CellPadding=”3″>
<Columns>
<asp:TemplateField HeaderText=”ID”>
<ItemTemplate>
<asp:Label ID=”lblId” runat=”server” Text='<% #Eval(“Id”) %>’ />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Image Name”>
<ItemTemplate>
<asp:Label ID=”lblImageName” runat=”server” Text='<% #Eval(“ImageName”) %>’ />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”Description” HeaderText=”Description” />
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID=”imgPhoto” Width=”100px” runat=”server” ImageUrl='<% #Eval(“ImagePath”) %>’ />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID=”btnImageDelete” runat=”server” SkinID=”btnRemove” Text=”Remove” OnClick=”btnImageDelete_Click” />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor=”White” ForeColor=”#000066″ />
<HeaderStyle BackColor=”#006699″ Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”White” ForeColor=”#000066″ HorizontalAlign=”Left” />
<RowStyle ForeColor=”#000066″ />
<SelectedRowStyle BackColor=”#669999″ Font-Bold=”True” ForeColor=”White” />
<SortedAscendingCellStyle BackColor=”#F1F1F1″ />
<SortedAscendingHeaderStyle BackColor=”#007DBB” />
<SortedDescendingCellStyle BackColor=”#CAC9C9″ />
<SortedDescendingHeaderStyle BackColor=”#00547E” />
</asp:GridView>
</div>
</div>
</div>

Admin Side .cs

protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“SelfAssessmentConnStr”].ConnectionString);

//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath(“SlideImages/” + filename));
//Open the database connection
con.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand(“Insert into SlideShowImage(ImageName,ImagePath,Description) values(@ImageName,@ImagePath,@Description)”, con);
//Passing parameters to query
cmd.Parameters.AddWithValue(“@ImageName”, filename);
cmd.Parameters.AddWithValue(“@ImagePath”, “SlideImages/” + filename);
cmd.Parameters.AddWithValue(“@Description”, txtDesc.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
txtDesc.Text = string.Empty;
BindDataList();

DataTable dt = ClsCommon.GetAdhocResult(“SELECT * FROM SlideShowImage”).Tables[0];
gvSlideEdit.DataSource = dt;
gvSlideEdit.DataBind();

BindData();
}

protected void BindDataList()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“SelfAssessmentConnStr”].ConnectionString);

con.Open();
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand(“SELECT ImageName,Description from SlideShowImage”, con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
con.Close();
}
public void DeletePysicalFiles(string fileName)
{
System.IO.File.Delete(Request.PhysicalApplicationPath + “SlideImages/” + fileName);
System.IO.File.Delete(Server.MapPath(“SlideImages/”) + fileName);
}

private void BindData()
{
//Bind the grid view
gvSlideEdit.DataSource = RetrieveImages();
gvSlideEdit.DataBind();
}
private DataSet RetrieveImages()
{
//if products is available in the viewstate, use that
//instead of fetching again from the database
//if (ViewState[“Image”] != null)
// return (DataSet)ViewState[“Image”];
//fetch the connection string from web.config
string connString = ConfigurationManager.ConnectionStrings[“SelfAssessmentConnStr”].ConnectionString;
//SQL statement to fetch entries from products
string sql = @”SELECT * FROM SlideShowImage Order By Id DESC”;
DataSet ds = new DataSet();
//Open SQL Connection
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//Initialize command object
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
//Fill the result set
adapter.Fill(ds);
}
}
//ViewState[“Image”] = dsProducts;
return ds;
}

protected void btnImageDelete_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
Int32 index = row.RowIndex;

String Id = ((Label)gvSlideEdit.Rows[index].FindControl(“lblId”)).Text;
String ImageName = ((Label)gvSlideEdit.Rows[index].FindControl(“lblImageName”)).Text;

try
{
DeletePysicalFiles(ImageName);

try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“SelfAssessmentConnStr”].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand(“DELETE FROM SlideShowImage WHERE Id=@Id”, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter(“@Id”, Id.Trim().ToString()));
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblImageMessage.Text = “File has been Deleted Successsfully from database”;
}
}
catch (Exception ex) { }
}
catch (Exception ex) { }

DataTable dt = ClsCommon.GetAdhocResult(“SELECT * FROM SlideShowImage”).Tables[0];
gvSlideEdit.DataSource = dt;
gvSlideEdit.DataBind();

BindData();
}

and thats it

Advertisements

One thought on “[ ASP .net C# jQuery SQL Server Database ] Dynamic Image Gallery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s