Introduction
In this blog, we will discuss how to create bootstrap carousel image slider with SQL server database in asp.net.We will save image path in SQL server table and image in the images folder of our project. We will display all uploaded images in Gridview with JQuery datatable.
Step 1. Open MS SQL Server of your choice and create a database table and a stored procedure as given below or copy and paste the below script.
USE [SampleDB2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ImageSlider](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [nvarchar](50) NULL,
[ImagePath] [nvarchar](100) NULL,
CONSTRAINT [PK_ImageSlider] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[spGetAllSliderImages]
as
begin
SELECT * FROM ImageSlider
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[spGetSliderImages]
as
begin
SELECT TOP 5 * FROM ImageSlider ORDER BY ID DESC
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[spInsertSliderImages]
(
@ImageName nvarchar(50),
@ImagePath nvarchar(100)
)
as
begin
insert into ImageSlider(ImageName,ImagePath)
values(@ImageName,@ImagePath)
end
GO
Step 2. Open the Visual Studio version of your choice and create a new web project with empty template and give it a meaningful name.In the created project, open webconfig file and add a database connection. Change data source and database name which you have created in your SQL server.
<connectionStrings>
<add name="DBCS" connectionString="data source=DESKTOP-K5N6EMF\SQLEXPRESS; database=SampleDB2; Integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step 3. Add a web form, right click on the project, add a new item, choose web form, give a meaningful name and click ok. Design the HTML as given below. Drag and drop repeater control, file upload control, button control and grid view control.
Add the following script and style links:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
Complete HTML code of page
<!DOCTYPE html>
<html>
<head runat="server">
<title>Carousel Slider</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#GridView1").prepend($("<thead></thead>").append($(this).find("tr:first"))).dataTable();
});
</script>
<style>
.carousel-inner img {
width: 100%;
height: 350px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h4 class="text-capitalize text-center">Bootstrap Carousel Image Slider with database in asp.net</h4>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="carousel-item <%#GetActiveClass(Container.ItemIndex) %>">
<img alt="<%#Eval("ImageName")%>" src="<%#Eval("ImagePath")%>" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<a class="carousel-control-prev" href="#myCarousel" data-slide="prev" role="button">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#myCarousel" data-slide="next" role="button">
<span class="carousel-control-next-icon"></span>
</a>
</div>
</div>
<div class="container">
<div class="card" style="margin-bottom: 15px">
<div class="card-header bg-primary">
<strong class="card-title text-uppercase text-white">carousel Slider Images</strong>
</div>
<div class="card-body">
<button type="button" style="margin-bottom:10px;" class="btn btn-primary rounded-0" data-target="#AddImage" data-toggle="modal">Add New Image</button>
<div class="modal fade" id="AddImage">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Choose Slider Image</label>
<div class="custom-file">
<asp:FileUpload ID="SliderFileUpload" runat="server" CssClass="custom-file-input" />
<label class="custom-file-label"></label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="btnUpload" runat="server" Text="Upload" CssClass="btn btn-primary rounded-0" OnClick="btnUpload_Click" />
<button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<asp:GridView ID="GridView1" ShowHeaderWhenEmpty="true" HeaderStyle-CssClass="bg-primary text-white" runat="server" AutoGenerateColumns="false" CssClass="table table-striped table-bordered">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" />
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<asp:ImageField DataImageUrlField="ImagePath" ControlStyle-CssClass="img-thumbnail" ControlStyle-Width="100" ControlStyle-Height="60" HeaderText="Image" />
</Columns>
<EmptyDataTemplate>No Record Available <b>Click Add New Image to add Record</b></EmptyDataTemplate>
</asp:GridView>
</div>
</div>
</div>
</form>
</body>
</html>
Step 4. Double click on upload button and write the following code given below.
Add the following namespace:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
Full C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace SliderDatabase
{
public partial class CarouselSlider : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
BindImageRepeater();
}
}
private void BindGridView()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spGetAllSliderImages", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet dt = new DataSet();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected string GetActiveClass(int ItemIndex)
{
if (ItemIndex == 0)
{
return "active";
}
else
{
return "";
}
}
private void BindImageRepeater()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spGetSliderImages", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet dt = new DataSet();
sda.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (SliderFileUpload.PostedFile != null)
{
string FileName = Path.GetFileName(SliderFileUpload.PostedFile.FileName);
//Save files to disk
SliderFileUpload.SaveAs(Server.MapPath("images/" + FileName));
//Add Entry to DataBase
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spInsertSliderImages", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("@ImageName", FileName);
cmd.Parameters.AddWithValue("@ImagePath", "images/" + FileName);
cmd.ExecuteNonQuery();
BindGridView();
BindImageRepeater();
}
}
}
catch (Exception)
{
}
}
}
}
Step 5. Run project ctr+F5
Final output