Rotating Image Slider With jQuery From SQL Database

Recently, I was working on an ASP.Net website. I would like to create a jQuery Image Slider that rotates images automatically. I have tried looking at tutorials around the web, but I can't find a good solution to this. This article will explain how to implement an Image Slider in ASP.Net. This article initially starts with uploading images to a SQL Server database table. So we make a database table in SQL Server to save images. As the article progresses it explains the implementation of fetching images from the Database. One of the important concepts in this article is of when we update images in an Image Slider. First before proceeding we need to understand what the Image Slider is

Know about Image Slider

The times when image effects were done with Flash are gone. Now, new technologies are available to change the way developers work (for example, jQuery). jQuery is light-weight and you can easily customize it. Now you can use jQuery for image effect instead of flash.

The Image Sliders are the perfect solution for a product, work and content showcase. The Image Sliders control is very useful for displaying images and photos and making the viewing of images more pleasant and interesting in our website.

Where can you use them?

Simply, it adds some pleasant and interesting way to show the images on your page and it is also an effective way to get more content into the relatively small space. If you have a product-based business then you can use the slider to showcase your products. If you are a writer then you could use the slider to showcase your books and so on.  

Now, let's see how to do that.

My database table

  1. CREATE TABLE [dbo].[Slider_Table](  
  2.       [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.       [Title] [varchar](100) NULL,  
  4.       [Description] [varchar](200) NULL,  
  5.       [ImageName] [varchar](100) NULL,  
  6.       [IsActive] [bitNULL,  
  7.    CONSTRAINT [PK_Slider_Table] PRIMARY KEY CLUSTERED  
  8.    (  
  9.       [Id] ASC  
  10. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  11. ON [PRIMARY] 

My table structure looks like:

Database Table

Now you have a database table. You need to insert the record in the database table. So create a simple page in Visual Studio that contains some ASP.Net controls, such as file upload, TextBox, CheckBox and Button. The form looks as in the following image.

Insert Image Form

Stored Procedure for insert and Update

You now need to create a Stored Procedure in SQL Server Database for inserting records into the table. Later in the article we use it to update records in the database table.

  1. Create procedure [dbo].[SliderInsertImage]  
  2. (  
  3. @Id int,  
  4. @Title varchar(100),  
  5. @Description varchar(200),  
  6. @ImageName varchar(100),  
  7. @IsActive bit,  
  8. @mode int  
  9. )  
  10. AS  
  11. if(@mode=0)  
  12. begin  
  13. insert into Slider_Table values(@Title, @Description, @ImageName, @IsActive)  
  14. end  
  15. else  
  16. Begin  
  17.       UPDATE Slider_Table SET Title=@Title, Description=@Description, ImageName=@ImageName, IsActive=@IsActive  
  18.       WHERE Id = @Id  
  19. End 

The back-end database work is now done. Now again move to the front-end to make a connection with the database. We store only the name of the image in the database table, the column called ImageName. The image will be saved in the application or server. So we make a folder on the server that contains all the uploaded images.

You will use the name like title, description and image name in this application so you can create a property for it in the class file under the app_code folder. The class file looks like the following:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. /// <summary>  
  6. /// Summary description for Slider  
  7. /// </summary>  
  8. public class Slider  
  9. {  
  10.     private int sID;  
  11.     private string sTitle;  
  12.     private string sDescription;  
  13.     private string sImageName;  
  14.     private bool sIsActive;  
  15.     public int ID  
  16.     {  
  17.         get  
  18.         {  
  19.             return sID;  
  20.         }  
  21.         set  
  22.         {  
  23.             sID = value;  
  24.         }  
  25.     }  
  26.     //To get or set the Title of Image  
  27.     public string Title  
  28.     {  
  29.         get  
  30.         {  
  31.             return sTitle;  
  32.         }  
  33.         set  
  34.         {  
  35.             sTitle = value;  
  36.         }  
  37.     }  
  38.     public bool IsActive  
  39.     {  
  40.         get  
  41.         {  
  42.             return sIsActive;  
  43.         }  
  44.         set  
  45.         {  
  46.             sIsActive = value;  
  47.         }  
  48.     }  
  49.     public string Description  
  50.     {  
  51.         get  
  52.         {  
  53.             return sDescription;  
  54.         }  
  55.         set  
  56.         {  
  57.             sDescription = value;  
  58.         }  
  59.     }  
  60.     public string ImageName  
  61.     {  
  62.         get  
  63.         {  
  64.             return sImageName;  
  65.         }  
  66.         set  
  67.         {  
  68.             sImageName = value;  
  69.         }  
  70.     }  
  71. } 

Now, double-click on the "Save" button and add the following code to it.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. public partial class SliderImageInsert : System.Web.UI.Page  
  11. {  
  12.     Slider sliderinsrt = new Slider();  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         Label1.Visible  =false ;  
  16.     }  
  17.     protected void Button1_Click(object sender, EventArgs e)  
  18.     {  
  19.         sliderinsrt.Title = TextBox1.Text;  
  20.         sliderinsrt.Description = TextBox2.Text;  
  21.         sliderinsrt.ImageName = FileUpload1.PostedFile.FileName;  
  22.         SaveImage();  
  23.         sliderinsrt.IsActive = CheckBox1.Checked;        
  24.         int mode=0;  
  25.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  26.         con.Open();  
  27.         SqlCommand cmd = new SqlCommand("SliderInsertImage", con);  
  28.         cmd.CommandType = CommandType.StoredProcedure;  
  29.         cmd.Parameters.AddWithValue("@Id", sliderinsrt.ID);  
  30.         cmd.Parameters.AddWithValue("@Title", sliderinsrt.Title);  
  31.         cmd.Parameters.AddWithValue("@Description", sliderinsrt.Description);  
  32.         cmd.Parameters.AddWithValue("@ImageName", sliderinsrt.ImageName);  
  33.         cmd.Parameters.AddWithValue("@IsActive", sliderinsrt.IsActive);  
  34.         cmd.Parameters.AddWithValue("@mode", mode);  
  35.         cmd.ExecuteNonQuery();  
  36.         Label1.Visible = true;  
  37.         Label1.Text = "Successfully Saved";  
  38.         con.Close();      
  39.         TextBox1.Text="";  
  40.         TextBox2.Text="";             
  41.         CheckBox1.Checked=false;  
  42.     }  
  43.     private void SaveImage()  
  44.     {  
  45.         string message = string.Empty;  
  46.         if (FileUpload1.HasFile)  
  47.         {  
  48.             string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);  
  49.             ext = ext.ToLower();  
  50.             if (ext == ".gif" || ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp")  
  51.             {  
  52.                 string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);  
  53.                 Session["fileName"] = fileName;            FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadSliderImage/" + fileName).Replace("\\", "//"));                 
  54.             }  
  55.             else  
  56.             {  
  57.                 message = "Invalid File Format";  
  58.             }  
  59.         }  
  60.     }  
  61. } 

The code above contains a method named "SaveImage()" that checks the uploaded file extension using GetExtension() method.

  1. string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);  

If the extension of the uploaded file is okay then you need to save the file on the server or application. To do that I have used the following code in the SaveImage Method.

  1. string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);  
  2. Session["fileName"] = fileName;  
  3. FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadSliderImage/" + fileName).Replace("\\", "//"));  

Now run the application and test it.

Running application

Now enter the title and description; tick on the CheckBox and upload a file. The form looks like the following image.

Uploaded file

Now click on the "Save" button.

Successfully Saved

Now open the SQL Server database and check the inserted title, description and upload file name in the table.

Inserted value in Database table

Now check the uploaded file on the server.

Solution Explorer

Similarly, you can upload more images on the server and save the name in the database table.

Now, you need to create a Stored Procedure in the SQL Server Database to select the top 4 images with an is active condition.

  1. create procedure [dbo].[SliderSlectImage]  
  2. AS  
  3. begin  
  4. select top(4)* from Slider_Table where IsActive ='1';  
  5. end 

Now again move to the front end to make a connection with the database. Now we will make an Image Slider control. In the Image Slider control the Image will be rotated. That means we need a data control to show the images. So you can drag and drop a Repeater control onto the form. The form has the following code:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>    
  4.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  5.     <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />  
  6.     <script src="Scripts/Demo.js" type="text/javascript"></script>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10. <div class="content">  
  11.         <div class="autoCneter">  
  12.             <div class="slider-wrapper theme-default">  
  13.                 <div id="nivo-slider" class="nivoSlider" style="width: 960px">  
  14.                     <asp:Repeater ID="Repeater1" runat="server">  
  15.                         <ItemTemplate>  
  16.                                 <img src='<%# Getpath()%><%# DataBinder.Eval(Container.DataItem, "ImageName")%>' title='<b><%# DataBinder.Eval(Container.DataItem, "Title")%></b> <br>  <%# DataBinder.Eval(Container.DataItem, "Description")%>'/>  
  17.                                <%-- <div class="discription">  
  18.                                    '<%# DataBinder.Eval(Container.DataItem, "Title")%> <%# DataBinder.Eval(Container.DataItem, "Description")%>'  
  19.                                     </div> --%>  
  20.                         </ItemTemplate>  
  21.                     </asp:Repeater>  
  22.                 </div>  
  23.             </div>  
  24.             <script type="text/javascript">  
  25.                 $(window).load(function () {  
  26.                     $('#nivo-slider').nivoSlider();  
  27.                 });  
  28.             </script>  
  29.         </div>  
  30.     </div>  
  31.     </form>  
  32. </body>  
  33. </html> 

In the head section you need to add two files, one for CSS and another file with jQuery Code.

  1. <link href="Styles/nivo-slider.css" rel="stylesheet" type="text/css" />  
  2. <script src="Scripts/Demo.js" type="text/javascript"></script>   

These files above are attached in the Zip file. You can download these files from the attached file.

The code above defines the Repeater control with an image control that is bound with title, description and the image path. The path defines the server path of the image using the GetPath Method name with an image name that is coming from the database table.

  1. <img src='<%# Getpath()%><%# DataBinder.Eval(Container.DataItem, "ImageName")%>' title='<b><%# DataBinder.Eval(Container.DataItem, "Title")%></b> <br>  <%# DataBinder.Eval(Container.DataItem, "Description")%>'/>   

Now bind the Repeater control with image name, Title and  Description. The following code does the binding:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. public partial class ImageSliderPage : System.Web.UI.Page  
  10. {  
  11.     DataTable dt = new DataTable();  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         imageslider();  
  15.     }  
  16.     protected string Getpath()  
  17.     {  
  18.         return ResolveUrl("~/UploadSliderImage/");  
  19.     }  
  20.     private void imageslider()  
  21.     {  
  22.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  23.         con.Open();  
  24.         SqlCommand cmd = new SqlCommand("SliderSlectImage", con);  
  25.         cmd.CommandType = CommandType.StoredProcedure;        
  26.         SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  27.         DA.Fill(dt);  
  28.        // dt = sliderhelper.GetsliderImage();  
  29.         Repeater1.DataSource = dt;  
  30.         Repeater1.DataBind();  
  31.     }  
  32. } 

In the code above SQLDataAdapter fetches the data from the database and fills the data in the DataTable. Now run the application and test it.

Image Slider

Now the Image Slider that rotates the images automatically and has the numbers 1 2 3 4 to select the image manually and you can also select the previous and next image. If you do't want to show the number then you can change it with any image that you like. Similarly you can change previous and next with the image.

Now add an image and CSS file in the head section of the application and run it. Then the Image Slider shows the image instead of the number.

Customize Image Slider

 

Updating Images in Image Slider

One of the important concepts of this article applies to when we update images in the Image Slider. Before updating images, you need to bind an image name with DropDownList. That means you can select an image name and update it. The following code defines how to bind a DropDownList with Image Name.

You need to create a Stored Procedure in the SQL Server Database to select the image's name. 

  1. Create procedure [dbo].[GetImageID]  
  2. AS  
  3. begin  
  4. select Id, ImageName  from Slider_Table  
  5. end 

The back-end database work has been done. Now again move to the front end to make a connection with the database to bind a DropDownList with an image name. Drag and drop a DropDownList control onto the form.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdateImage.aspx.cs" Inherits="UpdateImage" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <style type="text/css">  
  7.         .style1  
  8.         {  
  9.             color: #FFFFFF;  
  10.         }  
  11.     </style>  
  12. </head>  
  13. <body style="color: #FF66FF; background-color: #99FFCC">  
  14.     <form id="form1" runat="server">  
  15.     <div style="color: #FF33CC; background-color: #00CCFF"><span class="style1"><strong>Select Slider Image ID:</strong></span>  
  16.     <asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width="140px"  
  17.             AutoPostBack="True">  
  18.         </asp:DropDownList>  
  19.     </div>  
  20.     </form>  
  21. </body>  
  22. </html> 

Now bind the DropDownList control with the image name. The following code defines the binding code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. public partial class UpdateImage : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         ShowImageName();  
  14.     }  
  15.     private void ShowImageName()  
  16.     {  
  17.         DataTable dt = new DataTable();  
  18.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  19.         con.Open();  
  20.         SqlCommand cmd = new SqlCommand("GetImageID", con);  
  21.         cmd.CommandType = CommandType.StoredProcedure;  
  22.         SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  23.         DA.Fill(dt);  
  24.         if (!object.Equals(dt, null))  
  25.         {  
  26.             if (dt.Rows.Count > 0)  
  27.             {  
  28.                 DropDownList1.DataValueField = "id";  
  29.                 DropDownList1.DataTextField = "ImageName";  
  30.                 DropDownList1.DataSource = dt;  
  31.                 DropDownList1.DataBind();  
  32.                 DropDownList1.Items.Insert(0, "Select");  
  33.             }  
  34.         }  
  35.     }  
  36. } 

Now run the application and test it.

Image name with DropdownList

You now need to create a Stored Procedure in the SQL Server Database to show the title and description for update when we select an image from the DropDownList.

  1. Create procedure [dbo].[GetImagetitleandDescription]  
  2. (  
  3.  @id int  
  4. )  
  5. AS  
  6. begin  
  7.  select Title, Description,ImageName,Isactive from Slider_Table where id =@id  
  8. end   

Now when we select an image name from the DropDownList it will also show the image, title and description to update. The following code add with DropDropDownList.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdateImage.aspx.cs" Inherits="UpdateImage" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>    
  6.     <style type="text/css">  
  7.         .style1  
  8.         {  
  9.             color: #FFFFFF;  
  10.         }  
  11.     </style>  
  12. </head>  
  13. <body style="color: #FF66FF; background-color: #99FFCC">  
  14.     <form id="form1" runat="server">  
  15.     <div style="color: #FF33CC; background-color: #00CCFF"><span class="style1"><strong>Select Slider Image ID:</strong></span>  
  16.     <asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width="140px"  
  17.             AutoPostBack="True">  
  18.         </asp:DropDownList>  
  19.         <table cellpadding="2" cellspacing="2" width="100%">  
  20.             <tr>  
  21.                 <td align="right" width="30%" class="ManageCourseHeaderlabel">  
  22.                     Title:  
  23.                 </td>  
  24.                 <td align="left">  
  25.                     <asp:TextBox ID="TextBoxTitle" runat="server" CssClass="textbox"></asp:TextBox>  
  26.                     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBoxTitle"  
  27.                         ErrorMessage="Title can't be empty" CssClass="ErrorMessage"></asp:RequiredFieldValidator>  
  28.                 </td>  
  29.             </tr>  
  30.             <tr>  
  31.                 <td align="right" class="ManageCourseHeaderlabel" valign="top">  
  32.                     Description:  
  33.                 </td>  
  34.                 <td align="left">  
  35.                     <asp:TextBox ID="TextBoxdescription" runat="server" Height="100px" TextMode="MultiLine"  
  36.                         Width="90%" CssClass="textbox"></asp:TextBox>  
  37.                     <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBoxdescription"  
  38.                         ErrorMessage="Description can't be empty" CssClass="ErrorMessage"></asp:RequiredFieldValidator>  
  39.                 </td>  
  40.             </tr>  
  41.             <tr>  
  42.               <td align="left">  
  43.                 </td> <td align="left">  
  44.                      <asp:FileUpload ID="FileUpload1" runat="server" />  
  45.                     <asp:Image ID="Image1" runat="server" Width="59px" />  
  46.                 </td>  
  47.                 </tr>  
  48.             <tr>  
  49.                 <td align="right" class="ManageCourseHeaderlabel">  
  50.                     Is Active:  
  51.                 </td>                
  52.                 <td align="left">  
  53.                     <asp:CheckBox ID="IsActiveCheckBox" runat="server" />  
  54.                 </td>  
  55.             </tr>  
  56.             <tr>  
  57.                 <td>  
  58.                 </td>  
  59.                 <td align="left" class="addbutton">  
  60.                     <asp:Button ID="UpdateButton" runat="server" Text="Update"  
  61.                         onclick="UpdateButton_Click" />  
  62.                     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
  63.                 </td>  
  64.             </tr>  
  65.         </table>  
  66.     </div>  
  67.     </form>  
  68. </body>  
  69. </html>

Now bind the DropDownList control with an image name and select the image name to show the Title and Description. The following code defines the binding code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. public partial class UpdateImage : System.Web.UI.Page  
  10. {  
  11.     DataTable dt = new DataTable();  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         if (!IsPostBack)  
  15.         {  
  16.             ShowImageName();  
  17.             Label1.Visible = false;  
  18.         }  
  19.     }  
  20.     private void ShowImageName()  
  21.     {  
  22.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  23.         con.Open();  
  24.         SqlCommand cmd = new SqlCommand("GetImageID", con);  
  25.         cmd.CommandType = CommandType.StoredProcedure;  
  26.         SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  27.         DA.Fill(dt);  
  28.         if (!object.Equals(dt, null))  
  29.         {  
  30.             if (dt.Rows.Count > 0)  
  31.             {  
  32.                 DropDownList1.DataValueField = "id";  
  33.                 DropDownList1.DataTextField = "ImageName";  
  34.                 DropDownList1.DataSource = dt;  
  35.                 DropDownList1.DataBind();  
  36.                 DropDownList1.Items.Insert(0, "Select");  
  37.             }  
  38.         }  
  39.     }  
  40.     protected void UpdateButton_Click(object sender, EventArgs e)  
  41.     {  
  42.     }  
  43.     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)  
  44.     {  
  45.         if (DropDownList1.SelectedIndex != 0)  
  46.         {  
  47.             Slider sl = new Slider();  
  48.             sl.ID = int.Parse(DropDownList1.SelectedItem.Value);  
  49.             ViewState["SliderImageid"] = sl.ID;  
  50.             SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  51.             con.Open();  
  52.             SqlCommand cmd = new SqlCommand("GetImagetitleandDescription", con);  
  53.             cmd.Parameters.AddWithValue("@id", sl.ID);  
  54.             cmd.CommandType = CommandType.StoredProcedure;  
  55.             SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  56.             DA.Fill(dt);  
  57.             if (!object.Equals(dt, null))  
  58.             {  
  59.                 if (dt.Rows.Count > 0)  
  60.                 {  
  61.                     //ViewState["CategoriesData"] = dataSet.Tables[0];  
  62.                     TextBoxTitle.Text = dt.Rows[0][0].ToString();  
  63.                     TextBoxdescription.Text = dt.Rows[0][1].ToString();  
  64.                     Image1.ImageUrl = "~/UploadSliderImage/" + dt.Rows[0][2].ToString();  
  65.                     ViewState["imageurl"] = dt.Rows[0][2].ToString();  
  66.                     IsActiveCheckBox.Checked = (bool)dt.Rows[0][3];  
  67.                 }  
  68.             }  
  69.         }  
  70.         else  
  71.         {  
  72.             TextBoxTitle.Text = "";  
  73.             TextBoxdescription.Text = "";  
  74.             IsActiveCheckBox.Checked = false;  
  75.             Image1.ImageUrl = "";  
  76.         }  
  77.     }  
  78. } 

Now run the application and select an image name from the Database.

Update Image

Now at the end if you want to change the title, description and upload file then you need to first change the the title text or description and update another file. To do that you will call the insertupdate Stored Procedure first that is defined in the preceding code.

  1. Create procedure [dbo].[SliderInsertImage]  
  2. (  
  3. @Id int,  
  4. @Title varchar(100),  
  5. @Description varchar(200),  
  6. @ImageName varchar(100),  
  7. @IsActive bit,  
  8. @mode int  
  9. )  
  10. AS  
  11. if(@mode=0)  
  12. begin  
  13. insert into Slider_Table values(@Title, @Description, @ImageName, @IsActive)  
  14. end  
  15. else  
  16. Begin  
  17.       UPDATE Slider_Table SET Title=@Title, Description=@Description, ImageName=@ImageName, IsActive=@IsActive  
  18.       WHERE Id = @Id  
  19. End 

Now update Title, Description, upload file and isactive. The following code defines the C# code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.IO;  
  10. public partial class UpdateImage : System.Web.UI.Page  
  11. {  
  12.     DataTable dt = new DataTable();  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             ShowImageName();  
  18.             Label1.Visible = false;  
  19.         }  
  20.     }  
  21.     private void ShowImageName()  
  22.     {  
  23.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  24.         con.Open();  
  25.         SqlCommand cmd = new SqlCommand("GetImageID", con);  
  26.         cmd.CommandType = CommandType.StoredProcedure;  
  27.         SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  28.         DA.Fill(dt);  
  29.         if (!object.Equals(dt, null))  
  30.         {  
  31.             if (dt.Rows.Count > 0)  
  32.             {  
  33.                 DropDownList1.DataValueField = "id";  
  34.                 DropDownList1.DataTextField = "ImageName";  
  35.                 DropDownList1.DataSource = dt;  
  36.                 DropDownList1.DataBind();  
  37.                 DropDownList1.Items.Insert(0, "Select");  
  38.             }  
  39.         }  
  40.     }  
  41.     protected void UpdateButton_Click(object sender, EventArgs e)  
  42.     {  
  43.         int mode = 1;  
  44.         Slider slider = new Slider();  
  45.         slider.ID = (int)ViewState["SliderImageid"];        
  46.         slider.Title = TextBoxTitle.Text;  
  47.         slider.Description = TextBoxdescription.Text;  
  48.         slider.IsActive = IsActiveCheckBox.Checked;  
  49.         if (FileUpload1.HasFile)  
  50.         {  
  51.             slider.ImageName = FileUpload1.FileName;  
  52.             if (File.Exists(Server.MapPath("~/UploadSliderImage/" + slider.ImageName).Replace("\\", "//")))  
  53.             {  
  54.                 Label1.Visible = true;  
  55.                 Label1.Text = "File already exists";  
  56.                 return;  
  57.             }  
  58.             else  
  59.             {  
  60.                 if (File.Exists(ResolveUrl(Server.MapPath("~/UploadSliderImage/" + ViewState["imageurl"].ToString()))))  
  61.                 {                  File.Delete(ResolveUrl(Server.MapPath("~/UploadSliderImage/") + ViewState["imageurl"].ToString()));  
  62.                 }                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadSliderImage/" + slider.ImageName).Replace("\\", "//"));  
  63.                 Image1.ImageUrl = "~/UploadSliderImage/" + slider.ImageName;  
  64.                 Label1.Visible = true;  
  65.                 Label1.Text = "Updated Successfully";  
  66.             }  
  67.         }  
  68.         else  
  69.         {  
  70.             slider.ImageName = ViewState["imageurl"].ToString();  
  71.             Image1.ImageUrl = "~/UploadSliderImage/" + ViewState["imageurl"].ToString();  
  72.             Label1.Visible = true;  
  73.             Label1.Text = "Updated Successfully";  
  74.         }  
  75.         slider.IsActive = IsActiveCheckBox.Checked;  
  76.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  77.         con.Open();  
  78.         SqlCommand cmd = new SqlCommand("SliderInsertImage", con);  
  79.         cmd.CommandType = CommandType.StoredProcedure;  
  80.         cmd.Parameters.AddWithValue("@Id", slider.ID);  
  81.         cmd.Parameters.AddWithValue("@Title", slider.Title);  
  82.         cmd.Parameters.AddWithValue("@Description", slider.Description);  
  83.         cmd.Parameters.AddWithValue("@ImageName", slider.ImageName);  
  84.         cmd.Parameters.AddWithValue("@IsActive", slider.IsActive);  
  85.         cmd.Parameters.AddWithValue("@mode", mode);        
  86.         SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  87.         DA.Fill(dt);  
  88.     }  
  89.     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)  
  90.     {  
  91.         if (DropDownList1.SelectedIndex != 0)  
  92.         {  
  93.             Slider sl = new Slider();  
  94.             sl.ID = int.Parse(DropDownList1.SelectedItem.Value);  
  95.             ViewState["SliderImageid"] = sl.ID;  
  96.             SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
  97.             con.Open();  
  98.             SqlCommand cmd = new SqlCommand("GetImagetitleandDescription", con);  
  99.             cmd.Parameters.AddWithValue("@id", sl.ID);  
  100.             cmd.CommandType = CommandType.StoredProcedure;  
  101.             SqlDataAdapter DA = new SqlDataAdapter(cmd);  
  102.             DA.Fill(dt);  
  103.             if (!object.Equals(dt, null))  
  104.             {  
  105.                 if (dt.Rows.Count > 0)  
  106.                 {  
  107.                     //ViewState["CategoriesData"] = dataSet.Tables[0];  
  108.                     TextBoxTitle.Text = dt.Rows[0][0].ToString();  
  109.                     TextBoxdescription.Text = dt.Rows[0][1].ToString();  
  110.                     Image1.ImageUrl = "~/UploadSliderImage/" + dt.Rows[0][2].ToString();  
  111.                     ViewState["imageurl"] = dt.Rows[0][2].ToString();  
  112.                     IsActiveCheckBox.Checked = (bool)dt.Rows[0][3];  
  113.                 }  
  114.             }  
  115.         }  
  116.         else  
  117.         {  
  118.             TextBoxTitle.Text = "";  
  119.             TextBoxdescription.Text = "";  
  120.             IsActiveCheckBox.Checked = false;  
  121.             Image1.ImageUrl = "";  
  122.         }  
  123.     }  
  124. } 

Now run the application and test it.

Update

Now select an image name from the DropDownList.

Select Image name

Now update the description and upload a new image.

Update with description and image

Now click on the "update" button. 

Updated Successfully

Now check it in the database table.

Updated table