autocomplete extender problem? - asp.net

I am using autocomplete extender, i write a webservice the webservice is working fine when i run webservice. But when i run my aspx page it is not displaying any thing the autocomplete is not showing only text box is there. this is my code......
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
SqlConnection con;SqlDataAdapter da;
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] GetTitleInfo(string prefixText)
{
int count = 10;
string sqry = "select * from news_upload where newstitle like #prefixText";
da = new SqlDataAdapter(sqry, "server=localhost;database=tfcnew;user id=sa;password=sql123");
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 100).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["newstitle"].ToString (), i);
i++;
}
return items;
}
this is (above) service.
<asp:TextBox ID="txtcomplete" runat ="Server" ></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server" MinimumPrefixLength ="1" ServiceMethod ="GetSuggestions" ServicePath="~/WebService2.asmx" TargetControlID ="txtcomplete" >
</asp:AutoCompleteExtender>
This is aspx code..
can u help me. thank you.

Add "[System.Web.Script.Services.ScriptMethod]" before the class declaration
[System.Web.WebService(Namespace = "http://tempuri.org/")]
[System.Web.WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptMethod]
public class WebService : System.Web.Services.WebService {
...
...
...
if it is already in your code, You could check the service path. Use Fiddler or Firebug to see if there is an actual call to the service. if not working then set the servicepath from paga_Load event of your aspx page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
AutoCompleteExtender2.ServicePath = ResolveUrl("~/mywebservice.asmx")
End If
End Sub

Related

ajaxToolkit:CascadingDropDown got error

I want to create cascadingdropdown using ajaxtoolkit but having error.
since newer version of ajaxcontroltoolkit have remove ToolkitScriptManager, so i use scriptmanager
<ajaxToolkit:CascadingDropDown
ID="cdlOffice"
TargetControlID="DropDownList1"
PromptText="Select Office"
PromptValue=""
ServicePath="~/WebService1.asmx"
ServiceMethod="GetLocation"
runat="server"
Category="LocationId"
LoadingText="Loading..." />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="DropDownList1" CssClass="col-md-2 control-label">Location</asp:Label>
<div class="col-md-10">
<asp:DropDownList id="DropDownList1" runat="server" class="select2-me" data-placeholder="--SELECT--" data-rule-required="true" style="width:250px;" />
</div>
</div>
and WebService1.asmx as follow
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public CascadingDropDownNameValue[] GetLocation(string knownCategoryValues)
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetFloor(string knownCategoryValues)
{
string Location = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["LocationId"];
string query = string.Format("SELECT ITOFF_LEVEL, ITOFF_ID FROM ITOFF_TBL WHERE ITOFF_NAME = {0}", Location);
List<CascadingDropDownNameValue> Floor = GetData(query);
return Floor.ToArray();
}
private List<CascadingDropDownNameValue> GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ITFORMConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
values.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString()
});
}
reader.Close();
con.Close();
return values;
}
}
}
}
i'm having error showing
Unhandled exception at line 6, column 97862 in
http://localhost:60461/Scripts/WebForms/MsAjax/MicrosoftAjax.js
0x800a138f - JavaScript runtime error: Unable to get property
'webServiceFailedNoMsg' of undefined or null reference
all the code i learn from googling. is there anything missing or did wrong?
Try removing the String Param 'knownCategoryValues' from you getLocation() web method definition:
[WebMethod]
public CascadingDropDownNameValue[] GetLocation()
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
And remove locationID property from the from the Cascading DropDown definition.
Or, if you are getting the locationID from another dropdown then leave it in and define it as the ParentControlID

AutoCompleteExtender doesn't work

I want to use AutoCompleteExtender
but it doesn't work ,i put a break point in the web service but it doesn't enter the web service !!
<asp:TextBox ID="txt_empName" runat="server" Width="300px" ></asp:TextBox>
<cc1:AutoCompleteExtender ID="txt_empName_AutoCompleteExtender" runat="server"
CompletionListCssClass="autocomplete_completionListElement" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
CompletionListItemCssClass="autocomplete_listItem" Enabled="True" MinimumPrefixLength="4"
OnClientItemSelected="get_emp_num" UseContextKey="True" ServiceMethod="Get_Emp_AutoComplete"
ServicePath="~/EmpAutoComplete.asmx" TargetControlID="txt_empName" BehaviorID="ACE_empName"
EnableCaching="False">
</cc1:AutoCompleteExtender>
My web service :
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public List<string> Get_Emp_AutoComplete(string prefixText, int count, string contextKey)
{
//split the string in the text box to get the department equivalent to the last prefix text entered in the textbox after ',' or ';'
string[] s = prefixText.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
if (s.Length > 0)
{
prefixText = s[s.Length - 1].Trim();//Last item in the array
}
List<string> Emp_List = Get_RequestEmp(prefixText, contextKey);
return Emp_List;
}
public static List<string> Get_RequestEmp(string prefixText, string contextKey)
{
prefixText = prefixText.Trim().Replace(' ', '%');
DBConnection ConnectionObj = new DBConnection(CMSession.GetSession("code", HttpContext.Current), false);
string cmdText = "SELECT emp_num , trim(name) FROM grrt5emp WHERE name LIKE '%" + prefixText + "%' ORDER BY name";
DataTable dt = ConnectionObj.Return_DataTable(cmdText);
List<string> Emp_List = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
//Returning key-value pair
Emp_List.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
}
return Emp_List;
}
}
My AjaxToolkit version is :
3.0.30930.28736
This worked for me: https://www.c-sharpcorner.com/UploadFile/57a357/autocomplete-extender-in-Asp-Net/
I think you're just missing the asp:ScriptManager

ASP.NET C# - Dropdown list by using User Control

I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}

Search GridView

I have a guestbook at the moment displaying "comment", "comment_time", "user". I want to add a search box below and then search the gridview by "user" and then bind the data to a new grid view below. I am under strict instructions to have all data interactions passed via a web service.
I have a Web Method at the moment to get all the comments:
[WebMethod]
public DataSet SearchDatabase(string query)
{
DataSet ds = new DataSet();
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%query%'";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(queryStr, myConn);
myConn.Open();
myDataAdapter.Fill(ds, "Comments");
myConn.Close();
return ds;
}
Here's the front code:
<asp:Label ID="Label3" runat="server" Text="Search"></asp:Label><asp:TextBox ID="TextBoxSearch"
runat="server"></asp:TextBox><asp:Button ID="ButtonSearch"
runat="server" Text="Search" onclick="ButtonSearch_Click" />
<asp:GridView ID="GridView2" runat="server">
The code behind:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string query = TextBoxSearch.Text;
localhost.Service1 myws = new localhost.Service1();
ds = myws.SearchDatabase(query);
GridView2.DataSource = ds;
GridView2.DataBind();
}
It just doesn't do anything at all, page refreshes with no new GridView or any other action.
On another side note:
I have another input on the same page with a required field validator that doesn't let me search unless I fill the input with some text. How can I resolve this?
Thanks.
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%"+query+"%'";

How can I data bind <%# Eval("Object.Property")%> programmatically in VB.NET

I can bind a inner object property to gridview using the following setup at design time in an ASP.NET gridview
<asp:TemplateField HeaderText="ObjectName" >
<ItemTemplate>
<%# Eval("Object.property")%>
</ItemTemplate>
</asp:TemplateField>
but what I would like to do know is create this programmatically at runtime
i.e. define my columns, add them to the gridview and then databind
I'm not sure if this is what you want to achieve. But if you want to create columns dynamically according to your object's properties on runtime, have a look at following code(example is with BoundColumns, have a look at Volpa's answer when you need TemplateColumns):
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"></asp:GridView>
Codebehind:
Public Partial Class GridViewTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
Dim cList As New List(Of CustomClass)
For i As Int32 = 1 To 10
Dim c As New CustomClass
c.ID = i
c.Name = "Object " & i
cList.Add(c)
Next
Dim model As New CustomClass
For Each prop As Reflection.PropertyInfo In model.GetType.GetProperties
If prop.CanRead Then
Dim field As New BoundField()
field.HeaderText = prop.Name
field.DataField = prop.Name
Me.GridView1.Columns.Add(field)
End If
Next
Me.GridView1.DataSource = cList
Me.GridView1.DataBind()
End Sub
End Class
Public Class CustomClass
Private _id As Int32
Private _name As String
Public Property ID() As Int32
Get
Return _id
End Get
Set(ByVal value As Int32)
_id = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
One way would be to create a class that implements ITemplate interface:
public class PropertyTemplate : ITemplate
{
private string _value = string.Empty;
public PropertyTemplate(string propValue)
{
this._value = propValue;
}
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl(this._value));
}
}
Then in your code-behind assing the ItemTemplate as following:
myTemplateField.ItemTemplate = new PropertyTemplate(myBusinessObject.MyProperty);
Another way would be to use Page.LoadTemplate if your custom template resides in the separate .ascx file:
myTemplateField.ItemTemplate = Page.LoadTemplate("~/MyTemplate.ascx");
And the .ascx file will look like:
<%# Eval("MyProperty") %>

Resources