Autocomplete method not called using AutoExtender - asp.net

I have Ajax AutoExtender control asociated with textbox. Suggested data are selected from database. But my AutoComplete code is not even fired. What can be wrong with the code? Thanks.
<asp:TextBox ID="txtSports" runat="server" CssClass="textbox" placeholder="Sport"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="1" ServicePath="~/AutoComplete.asmx" CompletionSetCount="20" CompletionInterval="0000" EnableCaching="true" UseContextKey="True" ServiceMethod="GetCompletionList" TargetControlID="txtSports" runat="server"></ajaxToolkit:AutoCompleteExtender>
AutoComplete.asmx file:
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports AjaxControlToolkit
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class AutoComplete
Inherits System.Web.Services.WebService
<System.Web.Services.WebMethodAttribute, System.Web.Script.Services.ScriptMethodAttribute> _
Public Shared Function GetCompletionList(prefixText As String, count As Integer, contextKey As String) As String()
Dim listString As New List(Of String)()
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("SportovniPlanetaCS").ConnectionString.ToString()
Using conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand((Convert.ToString("SELECT Sport, SportId FROM Sports WHERE Sport LIKE #Sport")))
cmd.Parameters.AddWithValue("#Sport", prefixText)
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read()
listString.Add(AutoCompleteExtender.CreateAutoCompleteItem(dr("Sport").ToString(), dr("SportId").ToString()))
End While
End If
End Using
Dim str As String() = listString.ToArray()
Return str
End Function
End Class

Well i Don't think you need to use a separate WebService for it. you could create a web method and make it work.
You could see example here...
AutoComplete Demonstration

In AjaxToolKit add
OnClientItemSelected="ClientItemSelected"
add javascript
function ClientItemSelected(source, e)
{
source.get_element().value = (document.all) ? e._item.innerText : e._item.textContent;
var str = $('#<%=txtsports.ClientID %>').val();
}

Related

How to check the file is already uploaded or not by using Ajax File Upload?

I am asking a question about Ajax File Upload again.. T_T
I have an ASP.NET webform (using VB.NET) which is using Ajax File Upload. I update my database table whenever I upload a file. I am checking a file is already uploaded or not when I drag into my upload panel and click the upload button.
If the target file is already uploaded, I want to show my error label like 'the file is already uploaded' . But the label doesn't showing . I did debug to trace the result and the file is really existing and it went through my label text setting but didn't show on my form.
Which part of my code is being wrong? I hope someone can guide me.
here is my asp code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
//customize the drag panel
function AjaxFileUpload_change_text() {
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';
}
</script>
<div style="width:40%;padding:25px;margin-left:200px">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
<asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
<script>
function MyCompleteAll() {
$('cmdDone').click()
}
</script>
</div>
<asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>
.vb code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True) //customize ajax panel
lblmsg.Text = "" //error display
End Sub
Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filename As String = e.FileName.Split(".").First + "_" + fileupload + ".pdf"
Dim path As String = Server.MapPath("~/uploads/")
//to add a database table of files up-loaded.
Dim constr As String = CONN + g_schema
Using con As New MySqlConnection(constr)
con.Open()
'check file is already uploaded
Dim select_seq As String = "select fname from filetable where fname like '" +
e.FileName.Split(".").First + "%'"
Dim cmd As New MySqlCommand(select_seq, con)
Dim reader = cmd.ExecuteReader()
While reader.Read()
fname = reader(0).ToString
End While
con.Close()
//the file is already uploaded
If fname IsNot "" Then
lblmsg.Text = "Already uploaded. Please upload the other files."
Else
// Upload process code
End Sub
Thank you.
I going to suggest you check the file on the file upload done event.
So, we can THEN build up a list of files that exist - you have the possibility of more then one file up-load.
So, I suggest dropping in a text box to "hold" each bad (duplicate) file.
So, lets persist into session() the duplicate files (we can NOT use controls on the page in the 3 events (start, complete, complete all).
So, we have this code:
Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("DupList") = DupList
txtDups.Visible = False
Else
DupList = Session("DupList")
End If
End Sub
And say this markup - the text box, a grid view, and of course the FileUpload.
So, say this markup up:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
/>
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
<asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
</div>
So far - VERY good you have that JavaScript button click to get our VERY imporant and needed final post back when done.
So, a single file upload done event - looks like this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' now code to add say to a database table of files up-loaded.
' but FIRST CHECK if the file already exists
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now add to database
Dim NewRow As DataRow = rstFiles.NewRow
NewRow("FileName") = e.FileName
NewRow("UpLoadTime") = Date.Now
NewRow("User_id") = 1
NewRow("Size") = e.FileSize
NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
rstFiles.Rows.Add(NewRow)
MyRstUpdate(rstFiles, "MyUpLoadFiles")
End If
End Sub
So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.
Ok, so all files up-load - that js button click fires, and we now have this final code stub run:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
' this final code is triggered by the javascrpt "click" on
' all file uplaod done
' if there are some duplicates - dispay to user.
If DupList.Count > 0 Then
txtDups.Visible = True
For Each s As String In DupList
If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
txtDups.Text &= s & " already exists - skipped and not uploaded"
Next
End If
' now addtonal code - maybe display gird of up-loaded files
Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= #D"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#D", SqlDbType.DateTime).Value = Date.Today
Gfiles.DataSource = MyRstP(cmdSQL)
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
So, it will look like this:
We hit ok, and now we have/see this:
Ok, so now lets try to re-upload two files that exist.
We So, we will see this:
So, we persist that "bad" list, and skip/don't save the file in the complete event.
And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards
Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using cmdSQL
Using conn = New SqlConnection(My.Settings.TEST4)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rst As DataTable, strTable As String)
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
conn.Open()
da.Update(rst)
End Using
End Using
End Sub
Edit: Check for "confirmed" file
Follow up question was not only does the file exist, but at some point (or some how - not yet disclosed), the use has the means to check box, or change the status of the up-loaded files. And if file has not yet been confirmed, then we still allow up-loading.
So, the code in question would be this:
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F
AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists.
' file is confirmed - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it - (or not confirmed)

ASP.NET/VB.NET error message saying " '#ButtonName#' is not declared. It may be inaccessible due to it's protection level."

I'm adding to an existing web app that has ASP.NET on the front end and VB.NET on the back end. I'm getting this error when I try to compile the code:
'#ButtonName#' is not declared. It may be inaccessible due to it's
protection level.
Here is my ASP.NET code:
<ajaxToolKit:TabPanel ID="MedicaidDataSubTabReadyToBill" runat="server" HeaderText="Ready To Bill">
<ContentTemplate>
<asp:UpdatePanel ID="MedicaidDataReadyToBillPanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="formRow" style="border:1px">
<asp:Button runat="server" ID="btnSave" Text="Save" width="70px" Visible ='false'/>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</ajaxToolKit:TabPanel>
And here is the code behind that is referencing the button "btnSave":
Protected Sub MedicaidDataReadyToBill_Search_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MedicaidDataReadyToBill_Search.Click
If (String.IsNullOrEmpty(uxMedicaidDataReadyToBill_SchoolYear.Text) Or _
(Me.uxMedicaidDataReadyToBill_ddCategory.SelectedIndex = 0)) Then
lblPageError.Text = "*All fields are required."
Else
btnSave.Visible = True
End If
End Sub
I tried to initialize the btnSave at the start of the code behind sub but that didn't work. Please someone help me out. Thanks in advance.
Here is requested code:
Partial Class MedicaidBillingAdmin_medicaidbillingadmin
Inherits BasePage
Dim ChildGridUniqueID As String = String.Empty
Dim ChildGridEditIndex As Integer = -1
Dim NursingChildGridUniqueID As String = String.Empty
Dim NursingChildGridEditIndex As Integer = -1
Dim MedicaidDataGridUniqueID As String = String.Empty
Dim MedicaidDataGridEditIndex As Integer = -1
Dim MedicaidDataReadyToBillGridUniqueID As String = String.Empty
Dim MedicaidDataReadyToBillGridEditIndex As String = -1
Dim remoteDirectory As String = "//FromUHIN//"
Dim localDirectory As String = "C:\test\"
Dim port As Int32 = 22
Public ExpandLink As StringBuilder = New System.Text.StringBuilder("")
Public ExpandLink_Nursing As StringBuilder = New System.Text.StringBuilder("")
Public Class Medicaid_Students
Public Property strSchool_ID As String
Public Property strCat As String
Public Property strStudentID As String
Public Property strStudentDistID As String
Public Property strLastName As String
Public Property strFirstName As String
Public Property strDOB As String
Public Property strMedicaidID As String
Public Property strBillingCode As String
Public Property strIEPDueDate As String
Public Property intGrade As Int16
End Class
If the control "btnSave" is not recognized in the code behind, double check the designer file MedicaidBillingAdmin.aspx.designer.vb to make sure it's there. You might have to delete the designer file and create it again for the control to be accessible.

How to display image from the database, I'm using asp.net

I'm having a trouble with displaying my image from the database(i'm using sql server 2008)
It says "Could not create type 'LeaveApplication.EmployeePhoto'."
Employee.aspx
<asp:Image ID="empPic" runat="server" Height="200px" ImageUrl="~/Images/pic.jpg" Width="200px" /></div>
Employee.aspx.vb
Dim ses As String
ses = Session("ses_empNum")
txtEmployeeNum.Text = ses
'empPic.ImageUrl = "../usrcontrols/EmployeePhoto.ashx?EmpNum'" & ses & "'"
empPic.ImageUrl = "../usrcontrols/EmployeePhoto.ashx?id=idkey'" & ses & "'"
EmplpyeePhoto.ashx.vb
Imports System.Web
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Public Class PatientPhoto
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim ID As New String(context.Request.QueryString("ID"))
Dim sqlConn As New SqlConnection("server=192.168.6.7;uid=sa;pwd=da;database=payroll_hospital;multipleactiveresultsets=true")
sqlConn.Open()
ID = Replace(ID, "^", "'")
Dim sqlComm As New SqlCommand("select dbImage from patient_data.dbo.tbdbImage where " & ID, sqlConn)
'context.Response.Write)
'Exit Sub
'context.Session.Item("test") = "select dbImage from patient_data.dbo.tbdbImage where " & ID
Dim dr As System.Data.SqlClient.SqlDataReader
dr = sqlComm.ExecuteReader
If dr.Read Then
context.Response.BinaryWrite(dr.Item("dbImage"))
Else
'Response.Write("File Not Found.")
context.Response.Write("<img src=../images/blank.jpg>")
End If
sqlConn.Close()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Employee.ashx
I bet you renamed a code class somewhere but did not update the code behind page. The code behind page does not know what the name is when it changes by hand.
Look for somewhere where you modified the class name.
public MyChangedClass:Page{}
<%# CodeBehind="MyChangedClass.aspx.cs" Class="MyOldClassName" %>

Decoding HTML and databinding into a ASP.NET repeater

I have a separate page where I use the Server.HTMLEncode feature to encode HTML a user has entered inside of a HTMLEditorExtender on a TextBox.
I am trying to insert this HTML into a repeater like so:
<asp:Repeater id="articleList" runat="server">
<ItemTemplate>
<div class="itemtemplate">
<h2><%#Container.DataItem("Title")%></h2>
<h5>Category:</h5> <%#Container.DataItem("Category")%><br />
<%#Container.DataItem("decodedHTML")%>
<%#Container.DataItem("UserName")%>
<%#Container.DataItem("DateOfPost")%>
</div>
</ItemTemplate>
<AlternatingItemTemplate>
<div class="altitemtemplate">
<h2><%#Container.DataItem("Title")%></h2>
<h5>Category:</h5> <%#Container.DataItem("Category")%><br />
<%#Container.DataItem("decodedHTML")%>
<%#Container.DataItem("UserName")%>
<%#Container.DataItem("DateOfPost")%>
</div>
</AlternatingItemTemplate>
</asp:Repeater>
And my code behind:
Sub displayArticles()
Dim conn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
conn.Open()
Dim cmd As New OleDbCommand("SELECT * FROM [UserArticles] ORDER BY DateOfPost DESC", conn)
Dim inputString As String = "HTMLBody"
Dim decodedHTML As String = Server.HtmlDecode(inputString)
articleList.DataSource = cmd.ExecuteReader()
articleList.DataBind()
conn.Close()
End Sub
"HTMLBody" is the name of the field in my database with the encoded HTML in.
Unfortunately, I am receiving the error
"IndexOutOfRangeException was unhandled by user code".
There is obviously a problem here referring to the string decodedHTML in my Container.DataItem statement, so what am I doing wrong?
EDIT: code from the other page where the html is encoded:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If String.IsNullOrEmpty(TextBox1.Text) Then
ErrorMessage.Visible = True
ErrorMessage.Text = "Your submission is blank. Please write your article first"
Else
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into UserArticles(Title,Category,UserName,DateOfPost,HTMLPost) Values (#f1,#f2,#f3,#f4,#f5)"
Dim HTMLEncode As String = Server.HtmlEncode(TextBox1.Text)
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", ArticleTitle.Text)
cmd.Parameters.AddWithValue("#f2", CategoryDropDown.SelectedValue)
cmd.Parameters.AddWithValue("#f3", User.Identity.Name)
cmd.Parameters.AddWithValue("#f4", DateTime.Now.Date)
cmd.Parameters.AddWithValue("#f5", HTMLEncode)
oleDbConn.Open()
cmd.ExecuteNonQuery()
TextBox1.Text = Nothing
ArticleTitle.Text = Nothing
CategoryDropDown.ClearSelection()
End If
End Sub
From the looks of it, decodedHTML is just a string which you are creating in the code. This is not accessible through your .aspx page.
You should just be able to update your .aspx markup to;
<%#Server.HtmlDecode(Container.DataItem("[COLUMN_NAME"))%>
Where [COLUMN_NAME] is the actual Table Column which holds the encoded html value.

Passing Value doesn't appear?

I am new at ASP.net and VB.net.So i Learn from book beginning ASP.Net 3.5 in VB 2008
the code on select.aspx.vb are
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Public Class _Select
Inherits System.Web.UI.Page
Private Conn As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
FillAuthorList()
End If
End Sub
Private Sub FillAuthorList()
lstAuthor.Items.Clear()
' Define the Select statement.
' Three pieces of information are needed: the unique id
' and the first and last name.
Dim selectSQL As String = "SELECT Nama_Depan, Nama_Belakang, ID FROM Employee"
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
' For each item, add the author name to the displayed
' list box text, and store the unique ID in the Value property.
Do While reader.Read()
Dim newItem As New ListItem()
newItem.Text = reader("Nama_Depan") & ", " & reader("Nama_Belakang")
newItem.Value = reader("ID").ToString()
lstAuthor.Items.Add(newItem)
Loop
reader.Close()
Catch err As Exception
lblResults.Text = "Error reading list of names."
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
Protected Sub lstAuthor_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstAuthor.SelectedIndexChanged
' Create a Select statement that searches for a record
' matching the specific author ID from the Value property.
Dim selectSQL As String
selectSQL = "SELECT * FROM Employee "
selectSQL &= "WHERE ID='" & lstAuthor.SelectedItem.Value & "' "
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
reader.Read()
' Build a string with the record information,
' and display that in a label.
Dim sb As New StringBuilder()
sb.Append("<b>")
sb.Append(reader("Nama_Depan"))
sb.Append(", ")
sb.Append(reader("Nama_Belakang"))
sb.Append("</b><br />")
lblResults.Text = sb.ToString()
reader.Close()
Catch err As Exception
lblResults.Text = "Error getting author. "
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
End Class
And the select.aspx are
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Select.aspx.vb" Inherits="connn._Select" %>
<!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">
<div>
<asp:ListBox ID="lstAuthor" runat="server" ></asp:ListBox>
<br />
<asp:Label ID="lblResults" runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
I am trying when select Listbox with ID="lstAuthor" the label box will pass the value but it failed to show.
Set True to AutoPostBack property:
<asp:ListBox ID="lstAuthor"
runat="server"
AutoPostBack="True" ></asp:ListBox>

Resources