Auto populate AutoCompleteExtender with all possibilities on first click - javascript

I am trying to have autoCompleteExtender to populate on focus of a textbox all possibilities. So far I am having no luck. I have tried adding onfucus in the textbox tag to call a js function that calls the webmethod to populate from a datatable with no luck. The webmethod is being called but nothing shows up on the page. Only after typing something in the textbox does any suggestions turn up.
Here is the aspx page control:
<div title="Model" runat="server" style="text-align:left; padding:20px"><strong>Model</strong>
<asp:TextBox ID="tbModel" runat="server" onfocus="ModelTBOnFocus()"></asp:TextBox>
<div id="ModelListPlacement" style="height:100px; overflow-y:scroll;" ></div>
<ajaxToolkit:AutoCompleteExtender ID="tbModel_AutoCompleteExtender" runat="server" DelimiterCharacters=""
Enabled="True" ServiceMethod="GetListofModels" MinimumPrefixLength="1" EnableCaching="true"
ServicePath="" TargetControlID="tbModel" CompletionInterval="50" CompletionSetCount="40"
CompletionListElementID="ModelListPlacement"></ajaxToolkit:AutoCompleteExtender>
</div>
And Here is the CodeBehind webMethod:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetListofModels(string prefixText)
{
using (SqlConnection sqlconn = new SqlConnection(GetConnectionStringValue("")))
{
sqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT DISTINCT(Model) FROM Assets WHERE Model like '" + prefixText + "%' " + ModelQuery, sqlconn);
cmd.Parameters.AddWithValue("#Model", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> Models = new List<string>();
TextInfo myTI = CultureInfo.CurrentCulture.TextInfo;
for (int i = 0; i < dt.Rows.Count; i++)
{
string model = myTI.ToTitleCase(dt.Rows[i]["Model"].ToString().ToLower());
Models.Add(model);
}
return Models;
}
}
This is working code. I am just trying to get all possibilities to show up when the textbox is focused. Any help would be much appreciated. Thanks!
EDIT:
This js is working also, but I am not getting any suggestions until something is typed.
Here is the javascript code to call the function:
<script type="text/javascript">
function ModelTBOnFocus() {
PageMethods.GetListofModels("");
}
</script>

Found my answer:
In order to solve this problem I had to set the MinimumPrefixLength="0"

Related

Button not firing the third time - ASP.NET code behind C#

I have written a code for button click that should retrieve data from the database and display the data row wise as required. It is working Fine for the first two clicks and it is not firing for the third time... I really don't understand why Please any help.
thank you in advance
The button code
protected void NextButton_Click(object sender, EventArgs e)
{
c++; //integer created to iterate through rows of datatable
qno++; //just counts the rows begining from 1 and displays on page
SqlCommand lque = new SqlCommand("select * from questions where course='" + cour + "' and [group]='" + gr + "' and semester='" + sem + "'", con);
IDataReader rque = lque.ExecuteReader();
if (rque.Read())
{
DataTable dt = new DataTable();
dt.Load(rque);
QuestionNo.Text = Convert.ToString(qno);
Question.Text = dt.Rows[c].Field<string>(4);// only displaying the required columns.
RadioButton1.Text = dt.Rows[c].Field<string>(5);
RadioButton2.Text = dt.Rows[c].Field<string>(6);
RadioButton3.Text = dt.Rows[c].Field<string>(7);
RadioButton4.Text = dt.Rows[c].Field<string>(8);
}
}
source code for the button
<asp:Button ID="NextButton" runat="server" Text="Next" Width="111px" OnClick="NextButton_Click" />
i also checked the data is loaded without any errors into the datatable by passing the datatable as a source to the gridview, it shows all the rows in gridview but in the labels the first 2 rows only displaying. I also chekced the counting varible is only increasing 2 times.enter image description here
a few rows from the table that i am retrieving
Your variables(c for example) will be reset to 0 on every request(button-click). Http is stateless. So you need to persist this value somewhere else(i.e. Session, ViewState, Hiddenfield, etc).
For example with Session, which you should only use if this site has not too much traffic:
private int CurrentRowIndex
{
get
{
if (Session["CurrentRowIndex"] == null)
Session["CurrentRowIndex"] = 0;
return (int)Session["CurrentRowIndex"];
}
set => Session["CurrentRowIndex"] = value;
}
protected void NextButton_Click(object sender, EventArgs e)
{
int currentRowIndex = ++CurrentRowIndex;
// maybe you need this also for your other variables
// ...
}
You should also not read all rows if you only want one, you should modify your sql query. If you use MS SQL-Server you could use ROW_NUMBER function to select only the required row from DB.

How to add link button and pass parameter in gridview using asp.net dynamically?

I want to add a link button in grid view dynamically, that button should keep parameter and when user click the button it has to go to respective page where i map
For ex: If button text is "View more" when user clicks the button,button will pass 'id' value, it will move to Details.aspx?id=10 and on that page, it will show the data by retrieve from database using that id value.
I know how to retrieve data from database. But i don't know hot add link button with parameter.
Here this is my code
protected void Page_Load(object sender, EventArgs e)
{
// data load to grid view
loadDataTable();
}
private void loadDataTable()
{
DataSet ds = new DataSet();
DataTable dt;
DataRow dr;
DataColumn date;
DataColumn designation;
DataColumn experience;
DataColumn location;
DataColumn nationality;
DataColumn details;
dt = new DataTable();
date = new DataColumn("Date");
designation = new DataColumn("Designation");
experience = new DataColumn("Experience");
location = new DataColumn("Location");
nationality = new DataColumn("Nationality");
details = new DataColumn("Details");
dt.Columns.Add(date);
dt.Columns.Add(designation);
dt.Columns.Add(experience);
dt.Columns.Add(location);
dt.Columns.Add(nationality);
dt.Columns.Add(details);
dr = dt.NewRow();
dr["Date"] = "10/2/2016";
dr["Designation"] = "Asp.net";
dr["Experience"] = "5";
dr["Location"] = "Jeddah";
dr["Nationality"] = "Indian";
dr["Detais"] = ""; // ADD LINK BUTTON
dt.Rows.Add(dr);
ds.Tables.Add(dt);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
asp.net code
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</div>
I want to add link button in Details header.
please help me. I am new to gridview and asp.net
how about adding an anchor?
dr["Detais"] = "<a href='Details.aspx?id="+ dr["id"].ToString() + "' target='_blank'>View Details</a>";
I'm not sure about the id field but this will work
EDIT
Change the Details column into a Literal column with something like this:
<asp:TemplateField headertext="Details">
<ItemTemplate>
<asp:Literal id="Literal1" runat="server" text='<%# Eval ("Details") %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>

How to call javascript function from asp:textbox?

I am using textbox for searching items from data base and loading them in gridview and
i used custom paging on gridview to show only 25 records per page
and i found java script for searching records on client side as
script>
function filter2(phrase, _id) {
var words = phrase.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var ele;
for (var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
var displayStyle = 'none';
for (var i = 0; i < words.length; i++) {
if (ele.toLowerCase().indexOf(words[i]) >= 0)
displayStyle = '';
else {
displayStyle = 'none';
break;
}
}
table.rows[r].style.display = displayStyle;
}
}
</script>
and calling this as:
<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>
this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox
but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')"event in my asp textbox e-g
<asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" runat="server" AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />
but asp didn't allow me to do that..
i need your help to achieve this.
thanks in advance.
EDIT:
I need both searching (client side, server side) in single textbox
because
client side allow searching from loaded page of gridview and
server side allow searching from database on clicking
You could add the client attribute of rendered input control via code behind:
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}
EDIT:
After the right comment of #Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:
<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.
For example:
<asp:Label runat="server" ID="label">test</asp:Label>
<asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>
This is what we have in output:

Adding items to a ListBox without scrolling up

I have a ListBox that contains all the online users.
The users are loaded from a MySQL database and loaded into the ListBox every second.
When I add an Item to the ListBox the ListBox scrolls up, I do not want this to happen.
<asp:UpdatePanel ID="usersPanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListBox ID="lstUsers" runat="server" ViewStateMode="Enabled" AutoPostBack="True"></asp:ListBox>
<asp:Timer ID="mainTimer" runat="server" ontick="Timer1_Tick" Interval="1000"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Timer Code:
protected void Timer1_Tick(object sender, EventArgs e)
{
...
MySqlDataReader datareader = command.ExecuteReader();
if (datareader.HasRows) {
lstUsers.Items.Clear();
while (datareader.Read()) {
lstUsers.Items.Add(new ListItem(datareader.GetString(1), datareader.GetInt32(0).ToString()));}
}
}
I've tried to do it with javascript but I was unable to get/set the scrollbar position on the listbox
What is done here is to save the current selected on list on client side, and set it back after the panel have been updated with the new values.
<script type="text/javascript" language="javascript" >
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beighnloadinf);
prm.add_endRequest(EndRequest);
var selected = "";
//get selected index and store in variable
function beighnloadinf() {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
var listLength = sel.options.length;
for(var i=0;i<listLength;i++){
if(sel.options[i].selected){
selected =sel.options[i].value;
break;
}
}
}
// set selected index back afrer update finished
function EndRequest(sender, args) {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
sel.value = selected;
}
</script>
You can do the same thing and on code behind, you get the selected one, and place it after the new update of your list.
You shouldn't be clearing the control every second. This is your problem:
lstUsers.Items.Clear();
Simplest solution would be to compare you ListBox items with your data source using the Except method on IEnumerable.
You'll have to convert your data source to IEnumerable manually. See this post as to how to do that.
NOTE: You'll have to change the type for the extension method.
After that, you can loop through your difference set (the returned object for .Except()) and add them to your list box like this:
lstUsers.Items.Add("a new list item");

Javascript code to get ProductID?

I have a webservice that gets a ProductName and I need the Products that are dropped down from the AutoExtender to be links to each product's individual page.
Right now the URL gets filled with the ProductName, and not the ID:
Default.aspx?id=Test%20Product
needs to be
Default.aspx?id=519
*Note - this site is for internal use only, so we are not worried about getting hacked right now. We want the site to work.
I have been told that what I want to do is not possible by people on the forum for asp.net so I came here hoping for some help. I think it is the javascript that is getting the ProductName from the webservice, and I need it to get the ProductID. I tried rewriting the For Each loop to include ProductID instead of ProductName, but then the AutoCompleteExtender only shows IDs in the results instead of the ProductNames.
Javascript:
<script type="text/javascript">
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_value();
window.location = ("/Product/Default.aspx?id=" + value)
}
</script>
Here is the code for my autoCompleteExtender and the webservice:
<asp:TextBox ID="Search" runat="server" AutoComplete="off"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetProducts" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" OnClientItemSelected="AutoCompleteClientMethod">
</asp:AutoCompleteExtender>
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class ProductSearch
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetProducts(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select DISTINCT ProductID, ProductName FROM Product WHERE ProductName LIKE '%" & prefixText & "%' ORDER BY ProductName ASC"
Dim sqlConn As New SqlConnection
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("ProductName").ToString(), i)
i += 1
Next
Return items
End Function
End Class
Edit: Adding the way the search results used to show up before the switch to the AutoCompleteExtender. I have tried to incorporate this into what I have now, but I can't get anything to work right. Please note that this is the OLD code, what is above is all the code I am using NOW.
<div class="hiddenResults">
<ul id="hiddenResults" style="display:none;">
<asp:ListView ID="lvProducts" runat="server" DataSourceID="dsProducts">
<ItemTemplate>
<li><span class="title"><%# eval("ProductName") %></span></li>
</ItemTemplate>
</asp:ListView>
</ul>
</div>
I tried
<ul style="list-style:none;"><li><a href='/Product/Default.aspx?id=<%# eval("ProductID") %>'>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetProducts" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" OnClientItemSelected="AutoCompleteClientMethod">
</asp:AutoCompleteExtender></a></li></ul>
but having the autocomplete extender in a list keeps the results of the query from showing.
Edit: Working code:
For Each dr As DataRow In myTable.Rows
Dim id As String = dr("ProductID").ToString()
Dim name As String = dr("ProductName").ToString()
Dim item As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(name, id)
items.SetValue(item, i)
i += 1
Next
See this article, or this one.
In short, create your list items using CreateAutoCompleteItem(). Modify the loop in GetProducts to use CreateAutoCompleteItem():
For Each dr As DataRow In myTable.Rows
dim id as String = dr("ProductId").ToString()
dim name as String = dr("ProductName").ToString()
dim item as String = AutoCompleteExtender.CreateAutoCompleteItem(name, id)
items.SetValue(item, i)
i += 1
Next
That sends both the name and the id to the client. That step is crucial. (If there are syntax errors above, forgive me... It's been a long time since I coded much VB - mostly C# these days.)
Then modify your OnClientItemSelected handler to use get_key() instead of get_value() for the url:
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_key();
window.location = ("/Product/Default.aspx?id=" + value)
}
You need to wrap the href in single quotes, like this:
<a href='/Product/Default.aspx?id=<%# eval("ProductID") %>'>
Now, what are you trying to do with the autocomplete extender? Are you trying to load the results with JavaScript?

Categories

Resources