How to set filter functionality in dropdown using textbox using Database in asp.net c#
Many times we have seen that we click on
a city drop down and get a text-box with some cities name. In this article I
will show same thing. In the previous post we have shown the filter
functionality without database but in this article we will show with database.
Database:-
Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dropdownlistwithfilter.aspx.cs" Inherits="dropdownlistwithfilter" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script>
; (function ($) {
"use
strict";
var TinySelect = {
init: function ($el, options) {
$el.data("tinySelectObj", this);
this.config = $.extend({
showSearch: true,
txtLoading: "Loading...",
txtAjaxFailure: "Error...",
dataUrl: null,
dataParser: null
}, options);
this.state = {
container: null,
selectBox: null,
itemContainer: null,
searchContainer: null,
searchBox: null,
$el: null,
open: false,
ajaxPending: false,
selectedValue: -1,
originalItemData: [],
filteredItemData: []
};
this.readSelect($el);
this.createSelect($el);
},
createSelect: function ($el) {
// Create container for select, search and options
this.state.container = $("<div></div>").
addClass("tinyselect").
css({ width: $el.css("width") });
//
Create the select element
this.state.selectBox = $("<div></div>").
addClass("selectbox").
on("click", { self: this }, this.onSelectBoxClicked);
this.state.container.append(this.state.selectBox);
// Create container to hold search and results
this.state.dropdown = $("<div></div>").
addClass("dropdown").
hide();
this.state.container.append(this.state.dropdown);
// Add search as first element
if (this.config.showSearch)
this.createSearch(this.state.dropdown);
// Create ul to hold items
this.state.itemContainer = $("<ul></ul>").
addClass("itemcontainer");
this.state.dropdown.append(this.state.itemContainer);
//
this.createItems();
// Hide original select element and add new component to
below
$el.hide().after(this.state.container);
this.state.$el = $el;
// Hide select content when clicked elsewhere in the
document
$(document).on("click", { self: this }, this.onDocumentClicked);
},
createItems: function (selected) {
var l1, opt;
// Remove all
this.state.itemContainer.empty();
//
for (l1 = 0; l1 < this.state.filteredItemData.length;
l1++) {
opt = this.state.filteredItemData[l1];
var newLi = $("<li></li>").
text(opt.text).
addClass("item").
attr("data-value",
opt.val);
if (opt.val == this.state.selectedValue) {
this.state.selectBox.html(opt.text);
newLi.addClass("selected");
}
newLi.on("click", { self: this }, this.onSelectLiClicked);
this.state.itemContainer.append(newLi);
}
},
createSearch: function ($el) {
this.state.searchContainer = $("<div></div>").
addClass("searchcontainer");
this.state.searchBox = $("<input
type='text'></input>").
addClass("searchbox").
on("click", function (e) { e.stopPropagation();
}).
on("keyup", { self: this }, this.onSearchKeyPress);
this.state.searchContainer.append($("<span class='searchicon'></span>"));
this.state.searchContainer.append(this.state.searchBox);
this.state.dropdown.append(this.state.searchContainer);
},
readSelect: function ($el) {
var self = this;
$el.find("option").each(function (index) {
var opt = $(this);
self.state.originalItemData.push({
val: opt.val(), text: opt.text() });
});
this.state.filteredItemData = this.state.originalItemData;
this.state.selectedValue =
$el.val();
},
setAjaxIndicator: function (failure) {
this.state.ajaxPending = true;
this.state.itemContainer.empty();
if (this.state.searchContainer !== null)
this.state.searchContainer.hide();
var newLi = $("<li></li>");
if (!failure) {
newLi.text(this.config.txtLoading).
addClass("loadindicator");
} else {
newLi.text(this.config.txtAjaxFailure).
addClass("loaderrorindicator");
}
this.state.itemContainer.append(newLi);
},
onDocumentClicked: function (e) {
var self = e.data.self;
if (self.state.open)
self.onSelectBoxClicked(e);
},
onSearchKeyPress: function (e) {
var self = e.data.self,
sval =
$(e.currentTarget).val();
if (sval.length === 0) {
self.state.filteredItemData = self.state.originalItemData;
} else {
self.state.filteredItemData
= self.state.originalItemData.filter(function (item) {
return
item.text.toLowerCase().indexOf(sval) >= 0 ? true : false;
});
}
self.createItems();
},
onSelectBoxClicked: function (e) {
var self = e.data.self;
// Do nothing, if currently animating
if (self.state.dropdown.is(":animated"))
return;
// Close selectBox
if (self.state.open) {
self.state.open = false;
self.state.selectBox.removeClass("open");
self.state.dropdown.slideUp(100);
return;
}
// Open selectbox
if (self.config.dataUrl !== null) {
self.setAjaxIndicator(false);
$.ajax({
url:
self.config.dataUrl,
dataType: "json",
type: "GET"
}).done(function (data) {
self.onAjaxLoadSuccess(self, data); }).
fail(function (data) {
self.onAjaxLoadError(self, data); });
}
self.state.open = true;
self.state.selectBox.addClass("open");
self.state.dropdown.slideDown(100);
},
onAjaxLoadSuccess: function (self, data) {
self.state.ajaxPending = false;
if (self.config.dataParser !== null) {
data = self.config.dataParser(data,
self.state.selectedValue);
}
self.state.$el.empty();
data.forEach(function (v) {
if (v.selected)
self.state.selectedValue = v.val;
self.state.$el.append(
$("<option></option>").
text(v.text).
val(v.val)
);
});
self.state.$el.val(self.state.selectedValue);
self.state.originalItemData
= data;
self.state.filteredItemData
= data;
if (this.state.searchContainer !== null)
this.state.searchContainer.show();
self.createItems();
},
onAjaxLoadError: function (self, data) {
self.setAjaxIndicator(true);
},
onSelectLiClicked: function (e) {
var self = e.data.self,
item =
$(e.currentTarget);
self.state.dropdown.find("li").each(function () {
$(this).removeClass("selected");
});
item.addClass("selected");
self.state.selectBox.html(item.text());
self.state.selectedValue =
item.attr("data-value");
self.state.$el.val(self.state.selectedValue);
self.state.$el.trigger("change");
},
};
$.fn.tinyselect = function (options) {
if (typeof (options) != "undefined") {
}
return this.each(function () {
var sel =
Object.create(TinySelect);
sel.init($(this), options);
});
};
}(jQuery));
</script>
<style>
.tinyselect {
height: 34px;
display: inline-block;
min-width: 200px;
position: relative;
}
.tinyselect .selectbox {
position: absolute;
height: 100%;
width: 100%;
text-align: left;
border: 1px solid #ccc;
line-height: 32px;
padding-left: 10px;
box-sizing: border-box;
cursor: pointer;
border-radius: 3px;
white-space: nowrap;
overflow-x: hidden;
}
.tinyselect .selectbox::after {
content: ' ';
position: absolute;
right: 0px;
border-left: 1px solid #ccc;
height: 100%;
font-size: 10pt;
line-height: 34px;
padding: 0px 8px;
width: 10px;
background-color: #eee;
background-repeat: no-repeat;
background-position: center;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAJCAYAAADkZNYtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAABXSURBVChTjY0BCYBAFMWugw3MYRAbmMROhjGDFXQTThSfcoNx/P8HV2DEvUG7kxVTUPV+MWCKqt4fLJhC9y96TLH7yIz30PmTDjc09HX+ZUJj3ybC96UczHIuzhJ1BlkAAAAASUVORK5CYII=');
}
.tinyselect .selectbox.open::after {
content: ' ';
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAJCAYAAADkZNYtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAABYSURBVChTY8ABWqE0QZAOxP+hNF4gDMTvgBikGESD+DgByHqQQhjG6RwlIEZWCMMgcQywA4ixKQaJowAbIMamEIZB8nBwB4ixKYJhkDwYRAAxNgVomCECALjaLs5bhaybAAAAAElFTkSuQmCC');
}
.tinyselect .dropdown {
position: absolute;
width: 100%;
top: 33px;
border: 1px solid #ccc;
background-color: white;
z-index: 100;
box-sizing: border-box;
max-height: 200px;
overflow-x: hidden;
overflow-y: scroll;
}
.tinyselect .dropdown .searchcontainer {
padding: 5px;
}
.tinyselect .dropdown .searchbox {
width: 100%;
border: 1px solid #ccc;
font-size: 10pt;
line-height: 2em;
padding: 0 5px;
}
.tinyselect .dropdown .searchicon {
position: absolute;
top: 12px;
right: 8px;
width: 14px;
height: 14px;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAADESURBVDhPnZLBDcIwDEW7DIt0CmZgBW5tc2AAFugWDNB7FuDMAB0g+FV25AQLJA5Prb797djJUEoJmabptCzLVVjneb4Lo483yYYadqF0bBQkJzJdSJIOT/7RtPuKLmS0yPgCq+zhyGq+NYGU0tkCXvdQVNh68TgmX697JJahEf/uaAEWE80oMbb9OSPJus1jq5zA6SxmR0erJhFGM30h20kOk85WL5wCWogu3N9q3Y3QFM3Xw8D+adUn9QtvfEQJMWV4A2WMBVG/g0M8AAAAAElFTkSuQmCC');
}
.tinyselect .itemcontainer {
list-style: none;
margin: 0;
padding: 0;
}
.tinyselect .itemcontainer > li {
padding: 5px 2px;
}
.tinyselect .itemcontainer > li.item {
padding: 5px 10px;
}
.tinyselect .itemcontainer > li.selected {
background-color: #eee;
}
.tinyselect .itemcontainer > li.item:hover {
background-color: #1b6eab;
color: white;
}
.tinyselect .itemcontainer li.loadindicator {
padding: 15px;
font-weight: bold;
}
.tinyselect .itemcontainer li.loaderrorindicator {
padding: 15px;
font-weight: bold;
color: red;
}
</style>
<title>How to set filter functionality in dropdown using textbox
using Database in asp.net c#</title>
</head>
<body>
<form runat="server">
<div class="container">
<asp:DropDownList ID="select1" runat="server">
</asp:DropDownList>
<script>
/*
This parser won't respect "---" selection */
function dataParserA(data, selected) {
retval = [{ val: "-1", text: "---" }];
data.forEach(function (v) {
if (selected == "-1" && v.val == 3)
v.selected = true;
retval.push(v);
});
return retval;
}
/*
This parser let's the component to handle selection */
function dataParserB(data, selected) {
retval = [{ val: "-1", text: "---" }];
data.forEach(function (v) { retval.push(v); });
return retval;
}
/*
Create select elements */
$("#select1").tinyselect();
$("#havoc").show()
</script>
</div>
</form>
</body>
</html>
Code
behind (C#):-
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class dropdownlistwithfilter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dropdownliastbind();
}
}
protected void dropdownliastbind()
{
SqlConnection con = new SqlConnection("Data
Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User
ID=sa; password=12345678");
string com = "Select * from tblcity";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
select1.DataSource = dt;
select1.DataBind();
select1.DataTextField = "Cityname";
select1.DataValueField = "id";
select1.DataBind();
}
}
Out-Put:-
How to set filter functionality in dropdown using textbox using Database in asp.net c#
Reviewed by NEERAJ SRIVASTAVA
on
2:22:00 PM
Rating:
No comments: