asp.net Auto complete textbox from database - asp.net

I tried to make a text box which gives suggestions from database columns. However it's showing this error when i run that page .
Error -
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified.
asp code
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:AutoCompleteExtender ID="autoComplete1" runat="server"
EnableCaching="true"
BehaviorID="AutoCompleteEx"
MinimumPrefixLength="2"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
CompletionInterval="1000"
CompletionSetCount="20"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true"> </asp:AutoCompleteExtender>
<td><asp:TextBox ID="TextBox2" runat="server" CssClass="text_box" autocomplete="off"></asp:TextBox><br /><asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please Enter Client / Company Name" style="color:#f00; font-size:11px"></asp:RequiredFieldValidator></td>
vb code
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AutoComplete
Inherits System.Web.Services.WebService
Dim cn As New SqlClient.SqlConnection()
Dim ds As New DataSet
Dim dt As New DataTable
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, _
ByVal count As Integer) As String()
'ADO.Net
Dim strCn As String = _
"Data Source=SONAM-PC\SQLSERVER2008R2;Initial Catalog=Brandstik2; Integrated Security=True"
cn.ConnectionString = strCn
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cn
cmd.CommandType = CommandType.Text
'Compare String From Textbox(prefixText)
'AND String From Column in DataBase(CompanyName)
'If String from DataBase is equal to String from TextBox(prefixText)
'then add it to return ItemList
'-----I defined a parameter instead of passing value
'directly to prevent SQL injection--------'
cmd.CommandText = "select * from BrandstikTesti Where client_name like #myParameter"
cmd.Parameters.AddWithValue("#myParameter", "%" + prefixText + "%")
Try
cn.Open()
cmd.ExecuteNonQuery()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
Catch ex As Exception
Finally
cn.Close()
End Try
dt = ds.Tables(0)
'Then return List of string(txtItems) as result
Dim txtItems As New List(Of String)
Dim dbValues As String
For Each row As DataRow In dt.Rows
''String From DataBase(dbValues)
dbValues = row("client_name").ToString()
dbValues = dbValues.ToLower()
txtItems.Add(dbValues)
Next
Return txtItems.ToArray()
End Function
End Class

Add Top of your aspx page
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
Or You are missing dll

Related

Display a list of images in a gridview from SQL

Using VS2013 (asp.net, VB) and SQL Server 2012.
I have a table in my database that consists of columns ID, Name and ProfilePic. ProfilePic has a type of image.
I want to display a list of ALL of the images in a gridview. Looking at google I can only find examples where someone is selecting an image based on an ID which is not what I want.
Here is my imageHandler.ashx:
<%# WebHandler Language="VB" Class="profilePICHandler" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Public Class profilePICHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("nefsaConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from ProfilePics"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("profilepic"), Byte()))
dReader.Close()
con.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
On my aspx page I have this
<asp:GridView ID="gridSelectAPic" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image runat="server"
ImageUrl='<%# "ProfilePICHandler.ashx"%>'
ID="profilePIC" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And on the code behind I have this
Dim dt As New DataTable
Dim conn As New SqlConnection(ConnectionString)
Using conn
Dim ad As New SqlDataAdapter("Select * from ProfilePics", conn)
ad.Fill(dt)
End Using
gridSelectAPic.DataSource = dt
gridSelectAPic.DataBind()
I am at a bit of a loss how to proceed so any help greatly appreciated
Its because your handler is implemented wrong. You will need a querystring to tell the handler which image you have to retrieve.
You can use asp:ImageField for brevity and readability. Markup
<asp:ImageField HeaderText="Image"
DataImageUrlField="EmployeeID"
DataImageUrlFormatString="ProfilePICHandler.ashx?id={0}" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image runat="server"
ImageUrl='<%# Eval("EmployeeID", "ProfilePICHandler.ashx?id={0}")%>'
ID="profilePIC" />
</ItemTemplate>
</asp:TemplateField>
Now fetch from querystring from the generic handler like this
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("nefsaConnectionString").ConnectionString
Dim cmd As New SqlCommand()
cmd.CommandText = String.Format("select profilepic from ProfilePics where EmployeeID=", context.Request.QueryString("id"))
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("profilepic"), Byte()))
dReader.Close()
con.Close()
End Sub
Please note that
I have given the name EmployeeID for your PK in DB
Your handler name is Pascalcased on Eval and CamelCased at its implementation. Is it a typo?
Haven't parameterized the query for brevity.

ASP.net datatable is returning no values

i hope you can help with my issue. I'm trying to fill out a form from my database using a datatable. All seems to work fine but i get no data returned. Can anyone explain why? I've looked at the debug and there seems to be no errors and nothing looks like its failed. Here's my code behind (vb.net)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class _Default
Inherits System.Web.UI.Page
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Dim connection As New SqlConnection(constr)
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from tblContent WHERE CID = #ID", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#ID", Request.QueryString("ID"))
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
ID.Text = dt.Rows(0)("CID").ToString
TextBox2.Text = dt.Rows(0)("Heading").ToString
TextBox1.Text = dt.Rows(0)("ContText").ToString
Label2.Text = dt.Rows(0)("Location").ToString
End If
connection.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
getData(Me.User.Identity.Name)
End If
End Sub
Presentation layer:
<h2><asp:Label ID="Label2" runat="server" Text=""></asp:Label></h2>
<asp:TextBox ID="ID" runat="server" Visible="false"> </asp:TextBox><br />
<asp:Label ID="Label3" runat="server" Text="Heading" CssClass="label"></asp:Label>
<asp:TextBox ID="TextBox2" TextMode="SingleLine" Text="" runat="server"></asp:TextBox><br />
<asp:Label ID="Label1" runat="server" Text="Content" CssClass="label"></asp:Label><br />
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
I'm passing through the ID from another page via the query string (ID=5 as an example). There is data in my database and all labels/textboxes have the right IDs etc. I just can see what's wrong?
Thanks!
You could try to pass the correct type instead of string:
Using sqlDa As New SqlDataAdapter(sqlCmd)
Dim idParam = new SqlParameter("#ID", SqlDbType.Int)
Dim id As Int32
If Not Int32.TryParse(Request.QueryString("ID"), id) Then Throw New Exception("Not a valid ID-parameter!")
idParam.Value = id
sqlDa.SelectCommand.Parameters.Add(idParam)
sqlDa.Fill(dt)
End Using
By the way, also use the Using-statement for the connection. As an aside, you don't need to open/close the connection with SqlDataAdapter.Fill(table) since that is done automatically.

AutoCompleteExtender works fine on developing machine and it doesn't on pubblication server

Question tells all.
I got an AutoCompleteExtender that works as a clock on my pc running under VisualWebDeveloper's debug virtual machine but when I publish files on publication server it doesn't work...
This is the code i use in codebehind:
<System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod(EnableSession:=True)> Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager.ConnectionStrings("AFTERSALES").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "SELECT an_descr1, an_descr2 FROM anagrafica WHERE an_azienda = #azienda AND an_descr1 + ' ' + an_descr2 LIKE '%' + #SearchText + '%'"
cmd.Parameters.AddWithValue("#SearchText", prefixText)
cmd.Parameters.AddWithValue("#azienda", HttpContext.Current.Session("CODazienda").ToString)
cmd.Connection = conn
conn.Open()
Dim customers As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
customers.Add(Trim(sdr("an_descr1").ToString & " " & sdr("an_descr2").ToString))
End While
conn.Close()
conn = Nothing
Return customers
End Function
And here following are the controls i use in aspx search page (toolkitscriptmanager is in masterpage):
<asp:TextBox ID="TextBox1" runat="server" Width="300px" AutoPostBack="True"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServiceMethod="SearchCustomers"
MinimumPrefixLength="2" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" FirstRowSelected = "false"></ajaxToolkit:AutoCompleteExtender>

How to populate data from table to dropdown of gridview

dropdown in gridview
<asp:TemplateField HeaderText="ProjectModifiedBy" HeaderStyle-BackColor="#C0C0C0" HeaderStyle-BorderColor="Black">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" Width="99%" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code of web method
<WebMethod()> _
Public Function BindDropDown() As SqlDataReader
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlQuery As String
sqlQuery = "Sp_SelectEmpName"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlQuery, con)
cmd.CommandType = CommandType.StoredProcedure
Dim reader As SqlDataReader
con.Open()
reader = cmd.ExecuteReader()
Return reader
End Function
this is the code behind method which calls webmethod,what should i write here to bind the empname column data with dropdown of gridview
Private Sub BindDataDropDown()
End Sub

Can the results of my search be links to pages?

I have a search engine on my ASP.net 4.0 VB site that in which I need to link the search results with their individual pages. I understand that this can be done simply with a submit button after the search textbox but a submit button wouldn't fit next to the search bar on my page, plus it wouldn't look right.
The old way, the results were stored in a hidden div where they became links to their pages. I was hoping that the code I have of the old search could be incorporated into the new search, but I do not know where it would go. The only way I can think of to do it is to place the code in the webservice in a while or for loop. I may be way off base here, but that is why I am asking what the best way to go about this would be?
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select ProductName FROM Product WHERE ProductName LIKE '" & prefixText & "%'"
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
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ProductSearch.asmx" />
</Services>
</asp:ScriptManager>
<asp:TextBox ID="Search" runat="server" AutoComplete="off"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" CompletionListCssClass="results">
</asp:AutoCompleteExtender>
I used a little javascript to make links out of the results of my search engine query. This is what I have now - although the For Each loop in the Web Service doesn't work properly.
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_value();
window.location = ("/Product/Default.aspx?id=" + value)
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ProductSearch.asmx" />
</Services>
</asp:ScriptManager>
<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>
</asp:Content>
<WebMethod()> _
Public Function GetProducts(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select ProductID, ProductName FROM Product WHERE ProductName LIKE '" & prefixText & "%'"
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

Resources