autocomplete jquery asp.net c# - c#

my database table TAGS(TagId,TagName) my web method code is as follows
public List<Tag> FetchTagList(string tag)
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string query = "select * from TAGS Where TagName like '#myParameter'";
OleDbCommand cmd = new OleDbCommand(query,cn);
cmd.Parameters.AddWithValue("#myParameter", "%" + tag + "%");
try
{
cn.Open();
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
catch(OleDbException excp)
{
}
finally
{
cn.Close();
}
dt = ds.Tables[0];
List<Tag> Items = new List<Tag>();
Tag obj;
foreach (DataRow row in dt.Rows)
{
obj = new Tag();
//String From DataBase(dbValues)
obj.TagName = row["TagName"].ToString();
obj.ID = Convert.ToInt32(row["TagId"].ToString());
Items.Add(obj);
}
return Items;
}
}
i used class
public class Tag
{
public int ID { get; set; }
public string TagName { get; set; }
}
my javascript code is
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jsautocom/jquery.min.js" type="text/javascript"></script>
<script src="jsautocom/jquery-ui.min.js" type="text/javascript"></script><script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/FetchTagList",
data: "{ 'tag': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.TagName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
my aspx page is as like
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Search Tag: </label>
<asp:TextBox ID="TextBox1" class="tb" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" CssClass="btnSearch"
onclick="btnSearch_Click" Text="Search" />
</div>
</div>
but i get nothing.how to solve it.any one helps me is greatly appreciated.thanks in advance

just change the data and response in the ajax as given below
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
in your case change the PhoneContactName as something like the tag etc.,
hope this helps :D

There are 2 things to take care here:
A- make sure that you can call your service method, use [WebMethod] attribute over your function to make it available to be called over http.
you may also need to tune the WebService settings a little to make it to work.
B- Your javascript code is too much for this task.
considering what is written inside the official documentation of Autocomplete, you only need to point out 2 things:
Url of the fetching method,
The control that the user is going to write on, and will trigger the
autocomplete call using the current value inside.
Consider the following example:
$(".tb").autocomplete({source: "URL_OF_YOUR_REMOTE_METHOD"});
considering your example, you will need to put this code:
$(".tb").autocomplete({source: "WebService.asmx/FetchTagList"});
This is the minimal piece of code that you need in order to make it to work.
but to take everything manually as you did, is a little bit complicated and not that easy to figure our problem once they start to happen.
a live example: http://jsfiddle.net/grtWe/1/
just use this piece of code and let me know if it works, then we may go from here to achieve your goal.

if FetchTagList is your webmethod you are calling from jquery then don`t return list from method you can bind datatable directly to the autocomplete textbox just check following link how to do that.
http://nareshkamuni.blogspot.in/2012/06/sample-example-of-jquery-autocomplete.html
also you can do that using ajax autocomplete extender. for using ajax autocomplete extender refer following link
http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx

script is as follows:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Photos.aspx/GetAutoCompleteData",
data: "{'CategoryName':'" + document.getElementById("<%= txtCategory.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
web method:
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
string query = "select TagName from TAGS where TagName LIKE '%" + CategoryName + "%'";
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
//cmd.Parameters.Add("#ptext", System.Data.SqlDbType.NVarChar).Value = CategoryName;
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["TagName"].ToString());
}
return result;
}

C# code
One thing need to remember here, Json data we cannot create manually, create using JavaScriptSerializer Class
<%# WebHandler Language="C#" Class="CountryStateCityHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
public class CountryStateCityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["action"] != null)
{
string strCallbackFunf = string.Empty;
if (context.Request.QueryString["callback"] != null)
{
strCallbackFunf = Convert.ToString(context.Request.QueryString["callback"]).Trim();
}
if (context.Request.QueryString["action"] == "getcountry")
{
DataTable dt = GetDataTable("EXEC PR_GetCountries"); //GetDataTable need to write, this method will call the Database and get the result
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
context.Response.ContentType = "text/plain";
if (string.IsNullOrEmpty(strCallbackFunf))
{
context.Response.Write(serializer.Serialize(rows));
}
else
{
context.Response.Write(strCallbackFunf+"("+serializer.Serialize(rows)+");");
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
//HTML CODE or .aspx code and script needs to be attached.
<html>
<head>
<script src="../scripts/jquery-1.7.js"></script>
<link href="../scripts/jqueryui/development-bundle/themes/smoothness/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<link href="../scripts/jqueryui/development-bundle/demos/demos.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/javascript">
var CountriesTags; //Local variable to store json object
$(function () {
$("#lnkCountry")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.click(function () {
var wasOpen = $("#Country").autocomplete("widget").is(":visible");
$("#Country").autocomplete("widget").css("display", "none");
if (wasOpen) {
$("#Country").autocomplete("widget").css("display", "none");
return;
}
// Pass empty string as value to search for, displaying all results
$("#Country").autocomplete("search", "");
});
$("#Country").autocomplete({
source: function( request, response) {
var matcher = new RegExp("(^| )" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(CountriesTags, function (item) {
return matcher.test(item.label);
}));
},
minLength: 0,
select: function (event, ui) {
var sv = ui.item.label;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
change: function (event, ui) {
var sv = this.value;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
});
LoadCountry();
}
//html inputs Value are country id (<%=CountryID %>) and country name (<%=Country%>)
function LoadCountry() {
$.ajax({
url: "CountryStateCityHandler.ashx?action=getcountry",
dataType: "jsonp",
type: 'GET',
async: false,
success: function (data) {
CountriesTags = data;
//array of Json Object will return
//label, value and id are keys
//Example id:219 label:"United States" value:"United States"
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' - Method: Loading countries - ' + thrownError);
}
});
}
</script>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<input type="text" name="Country" id="Country" maxlength="50" size="20" class="TextBox" value="<%=Country%>" />
<input type="hidden" id="CountryID" name="CountryID" value="<%=CountryID %>">
</td>
<td>
<a style="height: 16px" id="lnkCountry"></a>
</td>
</tr>
</table>
</body>
</html>

Related

Jquery/Ajax autocomplete textbox not working in ASP.net

I have a text box that I am trying to have autocomplete with values from a database. The code is, however, not doing anything when I begin typing in the text box. Does anyone have any idea how to fix this? The Scripts are in the head of the page.
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle"></asp:TextBox>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#searchTitle").autocomplete({
source: function (request,response) {
var param = { posting_jobPosition: $("#searchTitle").val() };
$.ajax({
url: "jobseekerHome.aspx/GetTitles",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return {value: item }}))
},
});
},
minlength: 1
});
});
</script>
[WebMethod]
public static List<string> GetTitles(string posting_jobPosition)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(CS);
List<string> Titles = new List<string>();
string query = string.Format("SELECT posting_jobPosition FROM BusinessJobPosting WHERE (posting_jobPosition LIKE '%{0}%' AND isActive = true)", posting_jobPosition);
OleDbCommand oleCom1 = new OleDbCommand(query, Connection);
Connection.Open();
OleDbDataReader reader = oleCom1.ExecuteReader();
while (reader.Read())
{
Titles.Add(reader[0].ToString());
}
Connection.Close();
return Titles;
}
Thanks guys :)
One possible reason that I see is the ID. Change the id as:
$("#<%=searchTitle.ClientID%>").autocomplete({
related: Accessing control client name and not ID in ASP.NET

how to bind dropdown in sharepoint using angularJS?

Hi I am developing one small application in sharepoint 2013 webparts. I am trying to bind dropdown from database using angular js. My pages are RFRegretLetterWP.ascx and RFRegretLetterWP.ascx. I have tried as below.
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$http({
method: 'POST',
url: 'RFPRegretLetterWP.ascx/GetDDLNames',
data: {}
}).success(function (result) {
$scope.ProductList = result.d;
});
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
This is my html code.
<div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
<select ng-model="drpdpwnvalue" ng-options="item.OrderID for item in ProductList">
<option value="" label="Select and item"></option>
</select>
</div>
This is my server side code.
public static List<OrderList> GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
using (SqlConnection conn = new SqlConnection("I have connection string here"))
{
conn.Open();
string strquery = ("select * from CategoryMaster order by CategoryName Asc");
using (SqlCommand cmd = new SqlCommand(strquery, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
OrderList objorder = new OrderList(reader["Vendor_ID"].ToString());
list.Add(objorder);
}
}
}
return list;
}
public class OrderList
{
public string Vendor_ID;
public OrderList(string UName)
{
Vendor_ID = UName;
}
}
I have little doubt in making call to server. This is my Url
url: 'RFPRegretLetterWP.ascx/GetDDLNames' but my page name is RFPRegretLetterWP.ascx.cs so i am having confusion. In some articles i noticed [System.Web.Services.WebMethod()] but when i put it it gives me error. May I have some suggestions on this regards. thank you for consideration
I suggest you to insert the server side code into a LayoutsPage like this:
using System.Web.Services;
public partial class RFPRegretLetterWP : LayoutsPageBase
{
[WebMethod]
public static IEnumerable GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
/* your code */
return list;
}
public class OrderList
{
/* your code */
}
}
and call the web method with the url:
_spPageContextInfo.webAbsoluteUrl/_layouts/15/<project name>/<pagename>.aspx/GetDDLNames
like this:
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$.ajax({
type: "POST",
url: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/<project name>/RFPRegretLetterWP.aspx/GetDDLNames",
data: null,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: onCompleted,
error: onError
});
function onCompleted(data) {
if (data !== null)
$scope.ProductList = data.d;
}
function onError(error) {
console.log('An error has occurred: ' + error.data);
}
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
Replace <project name> with your visual studio project's name.

Complete TextBox AutoComplete Example – Getting data from database

I am trying to auto complete a text box with Names from a database. When I go to type in the text box when it is running nothing happens.
I have been following this tutorial but am unable to get it working.
http://www.dotnetodyssey.com/2015/01/14/autocomplete-textbox-using-jquery-asp-net-querying-database-complete-example/
Source code below.
The Aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function () {
$("#txtNames").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetNames",
data: "{'namePrefix':'" + $("#txtNames").val() + "'}",
dataType: "json",
minLength: 2,
success: function (data) {
response(data.d)
},
error: function (response) {
alert("Error" + res.responseText);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="txtNames">Names:</label>
<asp:TextBox ID="txtNames" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The Code Behind:
[WebMethod]
public static string[] GetNames(string namePrefix)
{
List<string> Name = new List<string>();
DataTable dtNames = new DataTable();
string sqlQuery = "select distinct Name from Houses where Name like '" + namePrefix + "%'";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(dtNames);
foreach (DataRow row in dtNames.Rows)
{
string name = Convert.ToString(row["Name"]);
Name.Add(name);
}
}
catch (Exception ex)
{
throw ex;
}
return Name.ToArray<string>();
}
Here is an example of autocomplete textbox:
private void LoadServices()
{
txtServiceName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtServiceName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtServiceName.AutoCompleteCustomSource = colValues;
}
And:
AutoCompleteStringCollection colValues = new AutoCompleteStringCollection();
private void GetAllServices()
{
// get list of Windows services
ServiceController[] services = ServiceController.GetServices();
List<string> ac = new List<string>();
// try to find service name
foreach (ServiceController service in services)
{
ac.Add(service.ServiceName.ToString());
}
colValues.AddRange(ac.ToArray());
}

How to use datatable from code behind in jqxgrid

Hi i have DataTable which is binding to Gridview. But in need to bind that know to jqxgrid or jqxdatatable. After googling so many times i didn't got proper solution for this.
DataTable tb1= qry.GetTicketDetails();
serviceWindow.DataSource = tb;
serviceWindow.DataBind();
This what i'm doing actully now.
IN jquery i can take XML shown in below.
var source =
{
dataType: "json",
dataFields: [
{ name: 'name', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'calories', type: 'int' },
{ name: 'totalfat', type: 'string' },
{ name: 'protein', type: 'string' }
],
id: 'id',
url: "data/ticket.XML", //how to take datatable from code behind file
};
.aspx code -->>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestCellSelection.aspx.cs" Inherits="CourierApp.Project.TestCellSelection" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title id='Description'></title>
<link rel="stylesheet" href="../JQWidgets/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../JQWidgets/scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.columnsresize.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/scripts/demos.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.pager.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxnumberinput.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxpanel.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.sort.js"></script>
<script type="text/javascript">
$(document).load(function () {
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#button").jqxButton({
theme: 'energyblue',
height: 30
});
$("#button").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});
//GetData
var data = {};
var dataFelds = {};
var dataCols = {};
GetDatas();
GetCol_Datafeilds();
GetCol_Columns();
function GetDatas() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/GridValues")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
data = response;
console.log(data);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Datafeilds() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Datafeilds")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataFelds = $.parseJSON(response);
console.log(dataFelds);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Columns() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Columns")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataCols = $.parseJSON(response);
console.log(dataCols);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
// prepare the data
var source =
{
datatype: "json",
datafields: dataFelds,
updaterow: function (rowid, rowdata, commit) {
// synchronize with the server - send update command
// call commit with parameter true if the synchronization with the server is successful
// and with parameter false if the synchronization failder.
commit(true);
},
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
width: 1000,
source: dataAdapter,
editable: true,
selectionmode: 'multiplecellsadvanced',
columnsresize: true,
columns: dataCols
});
// $('#jqxgrid').jqxGrid('pincolumn', 'From_KG');
//$("#jqxgrid").jqxGrid('enablehover', event.args.checked);
});
<%--$("#<%=btn_SelectCells.ClientID%>").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});--%>
</script>
</head>
<body class='default'>
<form id="form1" runat="server">
<div>
<div id='jqxWidget'>
<div id="jqxgrid">
</div>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get the selected cells" />
<%--<asp:Button ID="btn_SelectCells" runat="server" Text="Get the selected cells" UseSubmitBehavior="False" />--%>
</div>
</div>
</form>
</body>
</html>
.aspx.cs or Web Service Code ----->>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web.Script.Serialization;
using System.Web.Helpers;
using BL;
using DAL;
using Newtonsoft.Json;
public partial class Project_Service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region Testing
[WebMethod]
public static String GridValues()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
String Val = serializer.Serialize(rows);
if (Val != "")
{
return (Val);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Datafeilds()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = new Dictionary<string, object>();
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "string");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "number");
rows.Add(row);
}
counter += 1;
}
Col = serializer.Serialize(rows);
//Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Columns()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "100");
row.Add("cellsalign", "left");
//row.Add("pinned", "true");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "25");
row.Add("cellsalign", "right");
rows.Add(row);
}
}
Col = serializer.Serialize(rows);
// Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
#endregion
}
Paste it ......
Replace the Query by your Query.....
Donot Supply Datafeild and Column Def. in the .aspx page
It's Fully Dynamic Solution !!!

jquery autocomplete for multiple textboxes inside asp.net Gridview

I have asp.net Gridview that have at least 15 rows with textbox by default example
aspx
<asp:GridView ID="gv_Others" runat="server" AutoGenerateColumns="false" CssClass="gvothers">
<Columns>
<asp:TemplateField >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate >
<asp:TextBox ID="txtEmp" runat="server" Width=100% Height=22px CssClass="txtE"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs (here how I am generating 15 rows of a GridView)
private void SetInitialRowsofOthers()
{
var list = new List<string>();
for (int i = 0; i < 16; i++)
{
list.Add(string.Empty);
}
gv_Others.DataSource = list;
gv_Others.DataBind();
gv_Others.HeaderRow.Visible = false;
}
WevService.axms
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetotherServices(string txt1)
{
// your code to query the database goes here
List<string> result = new List<string>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["autoDBConn"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like #SearchText + '%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", txt1);
SqlDataReader obj_result1 = obj_Sqlcommand.ExecuteReader();
while (obj_result1.Read())
{
result.Add(obj_result1["txt1"].ToString().TrimEnd());
}
}
}
return result;
}
I want to fill each textbox by jQuery autocomplete.. for this I created a webservice and getting a value from jQuery.
How I am trying to achieve this task:
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
$($arrT).autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetotherServices",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
$("#<%=Txt_RegNo.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt' : '" + $("#<%=Txt_RegNo.ClientID %>").val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
</script>
<script type="text/javascript">
function Load_OtherService() {
var hv = $('input[id$=hdnOthers]');
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
var hv1 = "" + hv.val();
var va = hv1.split(',');
for (var j = 0; j < va.length; j++) {
var $txt = $arrT[j];
$($txt).val(va[j]);
}
}
</script>
Now for example when I type "Engine Work" in TEXTBOX 1 and select the value which populated by jQuery autocomplete("Engine Work") then second time when I type in other text box (TEXT BOX 2). It's only give me the "Engine Work" option to select.. which means after selecting any value (populated by jQuery autocomplete) I can't select any other value in other text boxes....
Example:- (See Image Below)
as you see i type Genral Work but still it`s populating the Previous value "Engine Work" in jquery AutoComplete which i dont want
How to find the TextBox by CSS Class using jQuery????
Something like this (its only find TextBox id by using jQuery inside GridView but I need to find textbox by Css Class)
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
Change your script block to this:
$(document).ready(function() {
// This selects all inputs inside the table with the txtE class and applies
// the autocomplete function to them
$('table[id$="gv_Others"] input.txtE').autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + request.term + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
});
Look at the data: in the ajax post - it's using request.term and I changed the selector.
The issue with your jquery is this line:
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
That will always return the first value of the array (the first textbox) so it's always submitting the first value to your webservice as the search text.
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace PlatForm_RollUp
{
/// <summary>
/// Summary description for SearchDPN
/// </summary>
public class SearchDPN : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
if (string.IsNullOrEmpty(prefixText)) { prefixText = "NA"; }
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["PPN_ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select DPN_Key, DPN, Item_Desc from Customer.DIM.PPN WHERE " +
"DPN like #SearchText+'%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
//StringBuilder sb = new StringBuilder();
List<string> _dpn = new List<string>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//sb.Append(string.Format("{0} - {1}", sdr["DPN"], sdr["Item_Desc"], Environment.NewLine));
_dpn.Add(sdr["DPN"].ToString() +" - " +sdr["Item_Desc"].ToString());
}
}
conn.Close();
context.Response.Write(new JavaScriptSerializer().Serialize(_dpn));
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
***************************
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
initializer();
});
var prmInstance = Sys.WebForms.PageRequestManager.getInstance();
prmInstance.add_endRequest(function () {
//you need to re-bind your jquery events here
initializer();
});
function initializer() {
$("[id*=txtDPN]").autocomplete({ source:
"/Handlers/SearchDPN.ashx" });
}
</script>

Categories