How to dispay data from q to textbox on VB.net - vb.net

this is stored procedure
this is Function for SelectOne
Public Function One(Id As Integer) As Object Implements IStudents.One
Try
Return db.SP_SelectOneStudent(Id).ToArray
Catch ex As Exception
Return False
End Try
End Function
Dim q = student.One(StudentID)

Assuming you want to show every field in the variable q into a TextBox:
...
Dim StringToShow as String = ""
For Each StringToAdd as String In q
StringToShow &= StringToAdd & " "
Next
YourTextBox.Text = StringToShow
...

Related

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Formatting 45.22.30 in VB.NET [duplicate]

Under keypress event, I have a function validating the entered characters, this is my code.
Public Function vNum2(val As Object)
Dim result As Boolean = False
Dim allowedChars As String = "0123456789." & vbBack
Try
If allowedChars.IndexOf(val) = -1 Then
result = True
End If
Catch ex As Exception
MsgBox("Error 1010xVNum2: " & ex.Message)
End Try
Return result
End Function
How do i validate a decimal when I entered more than 2 dots in decimal? When I press another dot, the textbox will not receive the character.
E.g: -> correct entry 45.23 receive the first dot.
-> validating entry 45.2.3 will not receive the next dot.
Try this :
Public Function vNum2(val As Object)
Dim result As Boolean = False
Try
'Dim allowedChars As String = "42.2.3"
Dim allowedChars As String = val.ToString()
'Bellow line will count how many dots are in string, if there one or none, result will be True
If allowedChars.Where(Function(dots) dots = ".").Count < 2 Then result = True
Catch ex As Exception
MsgBox("Error 1010xVNum2: " & ex.Message)
End Try
Return result
End Function

Query in VB.net sometimes doesn't work

I have a functionality which saves the information from a webform to the database, which is working fine.
This is my code for save functionality in Onspec.aspx.vb page
Public Sub SaveClick(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then
litMessage.Text = ""
Exit Sub
End If
Try
Dim sName As String = ""
With EmployerCandidate
.employerid = Master.Employer.ID
.employeruserid = 0
Try
.CVID = DocId
Catch
End Try
.Name = uxName.Text
.SurName = uxSurname.Text
Try
.PostCode = uxPostcode.Text
Catch ex As Exception
End Try
.Email = uxEmail.Text
Try
.MobileNo = uxMobileNo.Text
Catch ex As Exception
End Try
.OnSpec = True
.OnSpecType = uxOnSpecCategory.SelectedItem.Text
.Source = uxSourceID.SelectedItem.Text
.LastEmployer = uxEmployer.Text
.LastJobTitle = uxJobtitle.Text
.Profile = uxProfile.Text.Trim
End With
' email()
ResetForm()
panForm.Visible = False
panUpload.Visible = True
uxSubmit.Visible = False
uxUpload.Visible = True
litMessage.Text = "Thank you for submitting your details! We'll be in touch when appropriate vacancy arises. <a href='#' onclick='parent.$.colorbox.close()'>Close</a>"
UploadPanel.Visible = False
Response.Redirect("onspec-complete.aspx?e=" & Master.Employer.ID)
Catch ex As Exception
litMessage.Text = Core.Helper.FancyMessage("Error as occurred - " & ex.Message.ToString, "ERROR")
End Try
End Sub
Now, I want to send emails along with saving the data in the database so I added the following lines of code before ResetForm().
Dim specmatch As DataRow = DB.GetRow("SELECT TOP 1 name,email,password FROM [user] usr JOIN employeruser empUsr ON usr.id = empUsr.userid WHERE empUsr.empusertype = 1 AND empUsr.employerid = #eid ", DB.SIP("eid", LocalHelper.UserEmployerID))
If my query returns a value then I want to send email by calling the email function.
If specmatch IsNot Nothing Then
email()
End If
But in this line of code the employerid value is sometimes empty. It can't pick the id therefore it is returning an empty row. And therefore it's not calling the email function.
This id is the same as
.employerid = Master.Employer.ID
But if I replace the LocalHelper.UserEmployerID with Master.Employer.ID the form gives an error:
Object reference not set to an instance of an object.
employerid is an integer value.
I have also tried to add the following lines of code in this page(Onspec.aspx.vb)
Public ReadOnly Property EmployerId() As Integer
Get
Return Master.Employer.ID
End Get
End Property
But I get the same error:
Object reference not set to an instance of an object.
The above lines of code does not make any difference.
So I replaced Master.Employer.ID with LocalHelper.UserEmployerID
Where in localhelper.vb file (under appcode folder) it is determining employerid from the website with following lines of code.
Public Shared Function UserEmployerID() As Integer
If HttpContext.Current.Items("lh_useremployerid") Is Nothing Then
If LocalHelper.UserTypeCode = "e" Then
HttpContext.Current.Items("lh_useremployerid") = Core.DB.GetInteger("SELECT employerid FROM employeruser WHERE userid = " & LocalHelper.UserID)
Else
HttpContext.Current.Items("lh_useremployerid") = 0
End If
End If
Return HttpContext.Current.Items("lh_useremployerid")
End Function
These lines of code has been used in many places and works perfectly fine. In this case as well, it was working fine last Friday and now it's not. There was no changes made.
This is my email function
Private Sub email()
Dim strCandidateName As String = uxName.Text.Trim & " " & uxSurname.Text.Trim
Dim strCandidateSurname As String = uxSurname.Text
Dim strCandidateEmail As String = uxEmail.Text.Trim
Dim strCandidatePhone As String = uxMobileNo.Text.Trim
Dim strCPass As String = "mpb123"
Dim strContactType As String = "Speculative Application has been submited on the category of " & uxOnSpecCategory.SelectedItem.Text
Dim strContactMessage As String = uxProfile.Text.Trim
'''''''''''''''''''variable
Dim qq As String = String.Format("Select top 1 name, email, password FROM [user] WHERE id in (Select userid FROM employeruser WHERE empusertype=1 and employerid= " & LocalHelper.UserEmployerID & ")")
Dim drow As DataRow = Core.DB.GetRow(qq)
Dim semail As String = drow.Item("email").ToString
Dim sname As String = drow.Item("name").ToString
Dim spass As String = drow.Item("password").ToString
'''''''''''''''''''variable
Dim Email As Core.Email
'New Onspec Candidate Email sent to EmployerUser who is assigned to receive onspec email
Email = New Core.Email
With Email
.ContentID = 99
.Replacement("ContactName", strCandidateName)
.Replacement("ContactEmail", strCandidateEmail)
.Replacement("ContactTelephone", strCandidatePhone)
.Replacement("ContactType", strContactType)
.Replacement("ContactMessage", strContactMessage)
.Replacement("AdminContactName", sname)
.Replacement("AdminContactEmail", semail)
.Replacement("SiteName", LocalHelper.AppSetting("sitename"))
Dim attachments As New Generic.List(Of String)
If EmployerCandidate.CVID > 0 Then
Dim doc As New Document(EmployerCandidate.CVID)
attachments.Add(doc.PathOnDisc)
End If
.Attachments = Join(attachments.ToArray(), ";")
.Send()
End With
End Sub
GetRow function is defined in my database.vb page like following which is also used in many other places.
Shared Function GetRow(ByVal selectQueryText As String, ByVal ParamArray params As SqlParameter()) As DataRow
Return GetRowFromDB(selectQueryText, CommandType.Text, params)
End Function
And
Shared Function GetRowFromDB(ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataRow
Dim conn As SqlConnection = Nothing
Try
conn = GetOpenSqlConnection()
Return GetRowFromDB(conn, selectCommandText, selectCommandType, params)
Finally
If conn IsNot Nothing Then conn.Dispose()
End Try
End Function
Please suggest ways on how I can organize my code so that it works all the time.

Delete Keyword Count VB.net

I Have Problem About this count Keyword after that appear that stuff
Here Code
Public Sub searchayumiKn()
Dim myKeyWords() As String = TChat.Text.Split(" "c)
Dim mySQLQuery As String = "SELECT AIRes FROM T_GKnowledge WHERE "
Dim KeyWordCount As Integer
For KeyWordCount = 0 To myKeyWords.Length - 1
Dim strKeyParameter As String = String.Format("#Param{0}", KeyWordCount)
Dim strWhereClause As String
If KeyWordCount = 0 Then
strWhereClause = String.Format("Keyword LIKE {0}", strKeyParameter)
Else
strWhereClause = String.Format(" OR Keyword LIKE {0}", strKeyParameter)
End If
mySQLQuery &= strWhereClause
cmdhikari.Parameters.AddWithValue(strKeyParameter, String.Format("{0}{1}{0}", "%", myKeyWords(KeyWordCount)))
Next
With cmdhikari
.CommandText = mySQLQuery
.Connection = conayumi
End With
Try
dthikari = New DataTable
dahikari.Fill(dthikari)
answers.DataBindings.Add("text", dthikari, "AIRes", True)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Caution")
End Try
KeyWordCount = 0
TChat.Clear()
Return
End Sub
Got Error #param bla". can anyone delete this count?
i just need original of data record. Not Count every time. just not using count. so freely record
move out from for this declaration
Dim strKeyParameter As String = String.Format("#Param{0}", KeyWordCount)
Dim strWhereClause As String
it's make duplicate declaration the same parameter
hopefully could be useful
regards
Ade Nurhuda

'Value of type string cannot be converted to system.data.datatable' in vb.net

This is my code. I keep having an error "value of type string cannot be converted to system.data.datatable"
Function GetTable() As DataTable
Dim SQLConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Zeinchatconnection").ToString())
Dim CommSQL As New SqlClient.SqlCommand
Dim ChatDataAdapter As SqlDataAdapter
Dim paramSQL As SqlClient.SqlParameter
Dim DStable As DataSet
Dim table As New DataTable
Dim szName As String = ""
Dim szNumber As String = ""
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
End If
CommSQL.Connection = SQLConnection
CommSQL.CommandType = CommandType.StoredProcedure
CommSQL.CommandText = "spc_newselect"
CommSQL.ExecuteNonQuery()
ChatDataAdapter = New SqlDataAdapter(CommSQL)
ChatDataAdapter.Fill(DSTable)
table.Rows.Clear()
table.Clear()
table = DStable.Tables(0)
Dim i As Integer = 0
For i = 0 To table.Rows.Count - 1
szName = szName & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
szNumber = szNumber & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
Next
GetTable = "1"
Catch ex As System.Data.SqlClient.SqlException
GetTable = "0"
Catch ex As Exception
GetTable = "0"
If (IsNothing(ChatDataAdapter) = False) Then ChatDataAdapter.Dispose()
If (IsNothing(CommSQL) = False) Then CommSQL.Dispose()
SQLConnection.Close()
End Try
Return table
End Function
The part where the errors are is gettable= "1" and below.
GetTable = "1" indicates that you want to set the returnValue of your function. As your function is defined as Function GetTable() As DataTable your compiler shows an error!
A few lines below there is a correct return stmt (Return table) so I am not quite sure what your goal is with GetTable = "1"?
I would assume that you would like to have an additional returnValue indicating whether your function call was successful or not. But as a matter of fact functions may only have one returnValue.
You may choose to set your table var to nothing, or use a ref param ...
' possible solution 1 - using nothing value
Function GetTable() As DataTable
Try
' your code goes here
' remove GetTable = "1"
Catch ex as Exception
' change GetTable = "0" to
table = nothing
End Try
' other code ...
End Function
' possible solution 2 - ref param
Function GetTable(ByRef status as integer) as DataTable
Try
' your code goes here
' remove GetTable = "1"
status = 1
Catch ex as Exception
' change GetTable = "0" to
status = 0
End Try
' other code ...
End Function
At solution 2 you may also choose a boolean parameter indicating your call was successful or not.
Your function GetTable returns a DataTable
you can't convert "1" to a DataTable as the message suggests which is what is happening on the line GetTable = "1"
If you want to return a DataTable and Set a flag to see the status; change your function definition as so:
Function GetTable(byref result as Integer) As DataTable
Then instead of GetTable = "1" change this to result = 1. This way you can inspect the result value and return a DataTable:
Dim res as Integer
Dim dt as DataTable = GetTable(res)
If res = 1 then
'It worked!
End If
Side Note: Turn Option Strict On