I didn't write the function for the AutoCompleteExtender so I am not quite sure how to change it without screwing it up, so I figured I would ask here. Recently, it was requested that the AutoComplete show a product name & the date of launch of that specific product. I do not know how to add the date to the AutoComplete.
The reason this is needed is because the webinars we give out are shown again in the future, so there are multiple webinars with the same name in the database. It is a little difficult to choose one webinar when searching when there are 3 with the exact same name, so if it shows the name and the date, I would imagine it would be easier to choose the right one!
The way this is written right now is incorrect. I get a squiggly line underneath the word launchdate in the line Dim item As String = AjaxControlToolkit...... and the error is: Too many arguments to 'Public Shared Function CreateAutoCompleteItem(text As String, value As String) As String'
Any help is greatly appreciated! Like I said, I didn't write this, so I don't even know if this is best practice. I understand if you want to criticize the code, and I will change it if it needs it, but I would really like to know how to add the extra field too. Thanks!
Public Function GetProducts(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select DISTINCT ProductID, ProductName, LaunchDate
FROM Product
WHERE ProductName LIKE '%' + #prefixText + '%'
AND LaunchDate IS NOT NULL
ORDER BY ProductName ASC"
Using sqlConn As New SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
myCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText
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
Dim id As String = dr("ProductID").ToString()
Dim name As String = dr("ProductName").ToString()
Dim launchdate As String = dr("LaunchDate").ToString()
Dim item As String =
AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(name, id, launchdate)
items.SetValue(item, i)
i += 1
Next
Return items
End Using
End Function
Try this..
AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(name & " " & launchdate, id)
Related
Unable to get the excepted result due to the following error
Conversion from string " to type 'integer' is not valid'
I have been able to load values from the products table, add selected ones to Selected Products and then search all the selected products against the Customers table to find out how many customers ordered these products.
Try
Dim ListOfDiag As StringBuilder = New StringBuilder()
For Each row As DataGridViewRow In SelectedDiagDGV.Rows
ListOfDiag.Append(row.Cells(0).Value.ToString & "", "" & Environment.NewLine)
Next
Dim query As String = String.Empty
Dim SegmentConnectionString As String = "Data Source=Test-PC;Initial Catalog=TestDB;Integrated Security=True"
query = "SELECT Customers, ProductName from Customers WHERE ProductName in (" & ListOfDiag.ToString & ")"
Dim dTable As DataTable = New DataTable()
Dim dAdapter As SqlDataAdapter
dAdapter = New SqlDataAdapter(query, SegmentConnectionString)
dAdapter.Fill(dTable)
DataGridView1.DataSource = dTable
'Next
Catch ex As System. Exception
MsgBox(ex.Message.ToString)
End Try
Unable to perform a for loop search. Some of the values contain special characters example: Soft ’Drink’; Computer (Desk).
Error: Conversion from string " to type 'Integer' is not valid.
ListOfDiag.Append(row.Cells(0).Value.ToString & "", "" & Environment.NewLine)
There is no overload of StringBuilder.Append that takes (String, String) as arguments. the first string is row.Cells(0).Value.ToString & "" and then there is a comma between parameters and the second string is "" & Environment.NewLine Remember that "" is an empty string, not escape characters. Not sure what your intention was but this will not work.
You had the right approach; to build a string for the In clause. I used a List(Of String) to get the data from the rows then after the loop I used a .Join with a comma separator to get the value for the In clause.
I passed the connection string directly to the constructor of the Connection and passed the Select statement and the connection to the constructor of the Command. For the Select statement I used and Interpolated String (the string preceded by the $) You could also use String.Format in older version of Visual Studio.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I think the only special character that could mess things up would be the presence of a comma in a Product Name.
Private Sub OPCode()
Dim dTable As New DataTable
Dim ListOfDiag As New List(Of String)
For Each row As DataGridViewRow In SelectedDiagDGV.Rows
ListOfDiag.Add(row.Cells(0).Value.ToString)
Next
Dim InData = String.Join(",", ListOfDiag)
Using cn As New SqlConnection("Data Source=Test-PC;Initial Catalog=TestDB;Integrated Security=True")
Using cmd As New SqlCommand($"SELECT Customers, ProductName from Customers WHERE ProductName in ({InData})", cn)
cn.Open()
dTable.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dTable
End Sub
I'm trying to write a function that searches records in my database for the object of those that match the SearchCriteria. The functions parameters look like so:
RetrieveObject(SearchCriteria) As String (SearchCritera is a string aswell)
Right now for testing purposes I am using a console app that asks the user to search by first name.
Console.Writeline("Search by first name: ")
Dim firstName = Console.Readline()
I then use my function: RetrieveObject(firstName)
I want my function to show all the values (lastname, titlename, state, zip) for that particular person that was passed to the RetrieveObject function.
The problem I am having is that I cannot seem to understand how I'm going to match what the user enters with the value in the database.
If anyone could just put me in the right direction to help me understand how to accomplish this, I'd be so grateful!
Here is my code so far:
Private Function RetrieveObject(SearchCriteria As String) As String
Dim cn As OdbcConnection = New OdbcConnection(myCon)
Dim myQuery = "SELECT * FROM Applicant WHERE [strFirstName] LIKE '%son'"
Using com As New OdbcCommand(myQuery)
cn.Open()
com.Connection = cn
com.CommandType = CommandType.Text
com.CommandText = myQuery
com.Parameters.AddWithValue("#strFirstName", SearchCriteria)
Try
com.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
End Using
Return SearchCriteria
End Function
Thanks again!
To create a WHERE condition you need to provide (at the most basic level) three informations to the database engine. The first bit is the column name that you want to search for, the second piece is the operator that you want to use for matching records, and finally the value to search for
SELECT * FROM table WHERE FieldName = 'AStringValue'
Of course we could have a lot of variations with operators and field datatype but this answer is limited to your actual situation.
It is important to note that your query could return more than one record (in particular if you add wildcards operators as LIKE, so you cannot simply return a single value with this query, but instead you return a DataTable where you can loop over the Rows collection to see all the records returned by the query
So your code should be changed to
Private Function RetrieveObject(SearchCriteria As String) As DataTable
Dim myQuery = "SELECT * FROM Applicant WHERE [strFirstName] LIKE ?"
Try
Using cn = New OdbcConnection(myCon)
Using da = new OdbcDataAdapter(myQuery, cn)
da.SelectCommand.Parameters.Add("?", OdbcType.VarChar).Value = SearchCriteria
Dim dt = new DataTable()
da.Fill(dt)
return dt
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message.ToString())
return Nothing
End Try
End Function
Now you could call this method with something like
Dim table = RetrieveObject("John%")
if table IsNot Nothing Then
For Each row in table.Rows
Console.WriteLine(row["strFirstName"].ToString())
Next
End If
If you really need to return a json string with all the FirstName matched then you could add this to the last lines of the code above
.....
da.Fill(dt)
Dim names = dt.AsEnumerable().Select(Function(x) x.Field(Of String)("strFirstName")).ToArray()
string output = JsonConvert.SerializeObject(names);
return output;
And of course change again the return value to be a string.
You can also pass your search criteria into function which returns dataset as shown below , one more thing ,you can use the function in textbox textchange event in forms
Also while search include LIKE as LIKE '%" & #strFirstName & "%' which can help you narrow search results if needed
Public Function Search(ByVal Criteria As String) As DataSet
Try
Dim ds As New DataSet
Using sqlCon As New SqlConnection(connStr)
stQuery="SELECT * FROM Applicant WHERE [strFirstName]
LIKE '%" & #strFirstName & "%'"
Dim sqlCmd As New SqlCommand(stQuery, sqlCon)
Dim sqlAda As New SqlDataAdapter(sqlCmd)
sqlCmd.CommandType = CommandType.Text
sqlCmd .Parameters.AddWithValue("#strFirstName", Criteria )
sqlAda.Fill(ds)
End Using
Return ds
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
End Function
I am using VB.Net (Visual Studio 2013) and N-tier architecture to populate a combo box list. My code for the class is as below
Public Shared Function List() As List(Of AppName.BusinessLogic.BLL_RMCodeComboClass)
Dim dbo_RMCodeList As New List(Of AppName.BusinessLogic.BLL_RMCodeComboClass)
Dim connTemp As SqlConnection = AppClass.GetConnection
Dim strSelectSQL As String = "SELECT [RMCode] FROM [dbo].[RMMaster] WHERE [dbo].[RMMaster].[Category] = '" & strRMType & "'"
Dim strCommandSelect As New SqlCommand(strSelectSQL, connTemp)
Try
connTemp.Open()
Dim rdrTemp As SqlDataReader = strCommandSelect.ExecuteReader()
Dim clsdbo_RMCodeList As AppName.BusinessLogic.BLL_RMCodeComboClass
Do While rdrTemp.Read
clsdbo_RMCodeList = New BusinessLogic.BLL_RMCodeComboClass
clsdbo_RMCodeList.RMCode = System.Convert.ToString(rdrTemp("RMCode").ToString)
dbo_RMCodeList.Add(clsdbo_RMCodeList)
Loop
rdrTemp.Close()
Catch ex As SqlException
Throw ex
Finally
connTemp.Close()
End Try
Return dbo_RMCodeList
End Function
My objective is to retrieve or populate the combobox with RMCodes depending upon the type. Hence I have used the strSelectSQL accordingly. Please help me to pass the value of the Category to this function so that it becomes dynamic. The value of the Type is selected from another combo box on the presentation/UI layer and as such the Code field should be populated according to the Category chosen.
Thanks in advance
CL
E.g.
Private Function List(type As String) As List(Of Thing)
'...
Dim command As New SqlCommand("SELECT * FROM MyTable WHERE #Type IS NULL OR Type = #Type")
command.Parameters.Add("#Type",
SqlDbType.NVarChar,
50).Value = If(String.IsNullOrEmpty(type),
CObj(DBNull.Value),
type)
'...
End Function
That makes the filter optional. If you pass in Nothing or an empty String then the SQL parameter is NULL and every record matches, otherwise the result set is filtered by the value you pass in.
I created the coding for a program to check if table exists in database. But it keeps underlining restrictions in the coding.
Error 23 Value of type 'String' cannot be converted to '1-dimensional array of String'
Can you please tell me what i did wrong and check if the rest of my coding correct.
Here is the coding:
Dim cn As New SqlClient.SqlConnection(SQL_Loader("", My.Settings.SQL_Win_Auth, _
My.Settings.SQL_Username, My.Settings.SQL_Password, My.Settings.SQL_Server_Name, _
My.Settings.SQL_DB_Name))
Dim Cmd As New SqlClient.SqlCommand
Dim Reader As SqlClient.SqlDataReader
Cmd.Connection = cn
cn.Open()
Dim restrictions As String
restrictions = "Pastel_Companies"
Dim dbTbl As DataTable = cn.GetSchema("Pastel_Companies", restrictions)
If dbTbl.Rows.Count = 0 Then
MessageBox.Show("Table Does Not Exist")
Else
MessageBox.Show("Table exists")
End If
Thank you for any help given
The correct syntax to call GetSchema is the following
Dim restrictions As String() = new String() {Nothing, Nothing, "Pastel_Companies"}
Dim dbTbl As DataTable = cn.GetSchema("TABLES", restrictions)
The first parameter is the collection that you want to check for the existence of the object (in your case you want to check the TABLES collection)
The second parameter contains an array of restrictions. This array changes following the collection that you want to search. For the TABLES collection you should apply three restrictions database, owner and tablename.
The restrictions should appear in the exact order expected, and if you haven't a value to specify you pass a null value (Nothing in VB)
The offers a pretty good clue; you're passing a string as the second argument to GetSchema instead of a one-dimensional array of strings.
Try this:
Dim restrictions() as string = { Nothing, Nothing, "Pastel_Companies" }
Dim dbTbl As DataTable = cn.GetSchema("Tables", restrictions)
I am developing a VB.NET ASPX file. This report is currently working but now I want to add a parameter which should be an array list displaying all records from below SQL query:
" select distinct instrument_name AS instrument_name from FRUD.tblXref order by instrument_name "
But this array list displays "System.Data.Common" for all possible values from code:
Sub Main()
Dim pcSQL As String
Dim ProductList As New ArrayList()
pcSQL = " select distinct instrument_name AS instrument_name from FRUD.tblXref order by instrument_name "
Dim DBConn As SqlConnection
DBConn = New SqlConnection(ConfigurationManager.AppSettings("AMDMetricsConnectionString"))
DBConn.Open()
Dim reader As SqlDataReader
Dim DBCommand As New SqlCommand(pcSQL, DBConn)
reader = DBCommand.ExecuteReader()
dProdCodeSearch.DataSource = reader
dProdCodeSearch.DataBind()
reader.Close()
I am sure I am doing something wrong which is a really simple fix. This SQL Connection works for my data tables in this report. But this is only parameter that I set to SQL output.
You need to create a Collection that is storing the values from the database and then read those values into an array. Something like
Dim instrumentNames As New List(Of String)
While reader.Read()
instrumentNames.Add(reader.GetString("insturment_name"))
End While
dProdCodeSearch.DataSource = insturmentNames