Can the results of my search be links to pages? - asp.net

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

Related

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.

asp.net Auto complete textbox from database

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

display image from db alongside other webpage elements

A continuation of the question on display (not download) image from db
<%# Page Language="VB" AutoEventWireup="false" CodeFile="imgTest1.aspx.vb" Inherits="imgTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="background-color: aliceblue;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div style="background-color: burlywood;">
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?id=1" />
<br />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class imgTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("id") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "filename=" & dt.Rows(0)("name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("CapstoneConnectionString1").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
End Class
I can now display the image on the aspx page but only the image is being displayed, all other web elements are missing.
I can only think of one reason for this, given that following are true:
Page used to render contents is imgTest1.aspx as well as page used to return image is also imgTest1.aspx.
imgTest1.aspx is always invoked with query parameter, id.
because of this page always returns an image.
Can you change the code as follows and tell us how it works:
...
...
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?imageId=1" />
...
...
and in code-behind
If Request.QueryString("imageId") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")

Using SqlBulkCopy SqlRowsCopied to update a label

I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

dynamically build html table on page load

Edit for vhinn
I want it to look like this:
I am trying to build an html table dynamically on pageload with variables from a database.
this is an example strictly html http://jsfiddle.net/jdv590/daCum/1/
code:
Private Sub brothersgird()
Dim html As New StringBuilder
Dim sql As String = "select Name, Hometown, Picture, Class from brothers",
connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;",
conn As New OleDbConnection(connstring),
myCommand As New OleDbCommand(sql, conn),
namevar As String,
classvar As String,
hometownvar As String
Dim x As Integer = 1
conn.Open()
Dim dr As OleDbDataReader = myCommand.ExecuteReader
html.Append("<table>")
Do While dr.Read
' imagevar = dr("Picture")
namevar = dr("Name")
classvar = dr("Class")
hometownvar = dr("Hometown")
html.Append("<tr>")
Do While x < 4
html.Append("<td><p>" & namevar & "<br /> Hometown: " & hometownvar & "<br /> Class: " & classvar & "</p></td>")
x = x + 1
Loop
html.Append("</tr>")
x = 0
Loop
html.Append("</table>")
dr.Close()
conn.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
brothersgird()
'write to panel maybe with this idea:
seniorpanel.html=html ???
End Sub
aspx side:
<asp:Panel ID="seniorpanel" runat="server">
</asp:Panel>
in your markup:
<asp:Panel ID="seniorpanel" runat="server">
<asp:GridView ID="brothersgird" runat="server" ShowHeader="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
<%# Eval("Name")%><br />
Hometown:
<%# Eval("Hometown")%><br />
Class:
<%# Eval("Hometown")%>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
brothersgird.DataSource = SelectBrothers()
brothersgird.DataBind()
End If
End Sub
Private Function SelectBrothers() As DataTable
Dim sql As String = "select Name, Hometown, Picture, Class from brothers"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;"
Dim conn As New OleDbConnection(connstring)
Dim ds As New DataSet
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(sql, conn)
adapter.Fill(ds)
Return ds.Tables(0)
End Function
You familiar with DataGrids?
Client Side:
<asp:DataGrid runat="server" id="dataTable">
</asp:DataGrid>
Server Side:
//Get your data table from the database - let's say the variable is called dt
dataTable.DataSource = dt
dataTable.DataBind()
There is a lot more you can do with datagrids, but this should be enough to get you started if you decide to go this route.
Are you asking how to do this in javascript if you already have the data? If so an example would be kinda like this:
var row = document.createElement("TR");
var th1 = document.createElement("TH");
row.appendChild(th1);

Resources