VB.NET Database Retrieval - sql

I have a VB.NET application that has instant messaging-like functionality with a database. It can retrieve the values just fine, but the problem is the formatting isnt coming out right. I want the format to be as follows:
Sender: Message
(so...)
David: Hey guys
What I've tried below doesn't get me the result I'm looking for, it just prints the sender at the top of the rich textbox in my application and the message at the bottom, does anyone have any ideas?
'-------------------Retreives the message-------------------------------------------------------------
Dim sqlStr As String = "SELECT * FROM dojodb.chats"
Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(rdr)
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg-- ------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strSender &= CStr(tbl.Rows(rowIndex)("Sender")) & vbNewLine
strMessage &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut = strSender + ": " + strMessage
Next
txtGroupChat.Text = strOutPut
'Keeps the richtextbox scrolled to the bottom so that most recent msg is always shown
txtGroupChat.SelectionStart = txtGroupChat.Text.Length
txtGroupChat.ScrollToCaret()
strOutPut = "" 'clearing the string so that it does not print out duplicate info next time
strSender = ""
strMessage = ""
'-------------------------End Retrive---------------------------------------

I feel a bit embarrassed posting this, but...
strSender = CStr(tbl.Rows(rowIndex)("Sender")) & ": "
strMessage = CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut &= strSender & strMessage
What do you think vbNewLine does? Also, be careful of &=

Related

SQL Result to Global Variable

Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.

How do I code so only the combobox's that I select are displayed?

textbox1.text = "OS = " combobox1.selecteditem + environment.newline +
combobox2.selecteditem + environment.newline + combobox3.selecteditem +
environment.newline
Working with Visual Basic 2010
I'm trying to make a display show up as
"OS =" and lets say I chose "combobox3" I want it to look like
"OS = Windows"
instead of
"OS =
Windows"
my code done so fare is
String concatenation should be done with & instead of +. Also, remove environment.newline to get rid of the line breaks.
textbox1.Text = "OS = " & combobox1.SelectedItem & " " &
combobox2.SelectedItem & " " & combobox3.SelectedItem
If I'm misunderstanding the question and you're trying to avoid line breaks where there is no value you would do the following:
Dim strResult As String = "OS = " & Environment.NewLine
ComboBox1.SelectedIndex = 1
If ComboBox1.SelectedItem IsNot Nothing Then
strResult += ComboBox1.SelectedItem.ToString() & Environment.NewLine
End If
If ComboBox2.SelectedItem IsNot Nothing Then
strResult += ComboBox1.SelectedItem.ToString() & Environment.NewLine
End If
If ComboBox3.SelectedItem IsNot Nothing Then
strResult += ComboBox1.SelectedItem.ToString() & Environment.NewLine
End If
TextBox1.Text = strResult
I would use Linq personally. You don't have to worry about many If statements and checking if something is selected or not and also concatenating a string either or adding or removing CheckBox's if you plan to do so; it will grab all of them. If you plan to not include some then you would need to modify the query to fit. This is tried and tested as well.
Dim q As List(Of String) = (From s As ComboBox In Me.Controls.OfType(Of ComboBox).Reverse() Where s.SelectedItem IsNot Nothing Select CStr(s.SelectedItem) & Environment.NewLine).ToList
MsgBox("OS = " & String.Join("", q.ToArray)) 'Just for testing!

Report only shows the last record

I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.
It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report

ODBC - unable to allocate an environment handle

Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.

Keep checked items checked while searching in CheckedListBox

I'm having some problems with VB.
I'm trying to create code that will keep the checked items in a CheckedListBox while you search through it. I have an array that stores the names of the checked items, but when you use the CkeckedListBox.SetCheckedItem() method, you need to use indices, and those change every time I search in the list box.
This is what I have so far:
Dim checkeditems(1000) As String
If txtSearch.Text.Length = 1 Then
For i = 0 To 1000
If lstVerktyg.CheckedItems.Item(i) = "" Then
Exit For
End If
checkeditems(i) = lstVerktyg.CheckedItems.Item(i)
Next
End If
Dim Connection As New MySqlConnection("server=" & My.Settings.Host & ";user id=" & My.Settings.User & "; password=" & My.Settings.Pass & "; port=3306; database=" & My.Settings.DB & "; pooling=false")
Try
Connection.Open()
Catch ex As MySqlException
Exit Sub
End Try
Dim Reader As MySqlDataReader
Dim Query As MySqlCommand
Dim ResultsNumber As Integer = 0
lstVerktyg.Items.Clear()
Query = New MySqlCommand("SELECT `namn` FROM `verktyg` WHERE `namn` LIKE '%" & txtSearch.Text.Replace("'", "\'") & "%' LIMIT 300;", Connection)
Reader = Query.ExecuteReader()
While (Reader.Read())
lstVerktyg.Items.Add(Reader.GetString("namn"))
End While
If Reader IsNot Nothing Then Reader.Close()
For i = 0 To 1000
If checkeditems(i) = "" Then
Exit For
End If
If lstVerktyg.GetItemChecked(i) Then
End If
Next
What do I do?
Here is a simple example of how you can do that. Let's say you initially fill a CheckedListBox control with some items, like this:
CheckedListBox1.Items.AddRange({"Item 1", "Item 2", "Item 3"})
Then, you show the form and let the user check whatever items they choose. Then, when you want to reload the list and retain which items are checked, you can do it like this. First, you want to create a list of all the checked items:
Dim checkedItems As New List(Of Object)(CheckedListBox1.CheckedItems.Count)
For Each i As Object In CheckedListBox1.CheckedItems
checkedItems.Add(i)
Next
Then, you can safely clear the items from the CheckedListBox:
CheckedListBox1.Items.Clear()
Then, you can reload the list with refreshed data, for instance:
CheckedListBox1.Items.AddRange({"Item 1", "Item 2", "Item 3", "Item 4"})
Then, you can loop through the items in the CheckedListBox and check each one if it exists in the saved list of checked items:
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
If checkedItems.Contains(CheckedListBox1.Items(i)) Then
CheckedListBox1.SetItemChecked(i, True)
End If
Next
So, to apply that method to your code example, it would look something like this:
Dim checkedItems As New List(Of Object)(lstVerktyg.CheckedItems.Count)
If txtSearch.Text.Length = 1 Then
For Each i As Object In lstVerktyg.CheckedItems
If i = "" Then Exit For
checkedItems.Add(i)
Next
End If
Dim Connection As New MySqlConnection("server=" & My.Settings.Host & ";user id=" & My.Settings.User & "; password=" & My.Settings.Pass & "; port=3306; database=" & My.Settings.DB & "; pooling=false")
Try
Connection.Open()
Catch ex As MySqlException
Exit Sub
End Try
Dim Reader As MySqlDataReader
Dim Query As MySqlCommand
Dim ResultsNumber As Integer = 0
lstVerktyg.Items.Clear()
Query = New MySqlCommand("SELECT `namn` FROM `verktyg` WHERE `namn` LIKE '%" & txtSearch.Text.Replace("'", "\'") & "%' LIMIT 300;", Connection)
Reader = Query.ExecuteReader()
While (Reader.Read())
lstVerktyg.Items.Add(Reader.GetString("namn"))
End While
If Reader IsNot Nothing Then Reader.Close()
For i As Integer = 0 To lstVerktyg.Items.Count - 1
If checkedItems.Contains(lstVerktyg.Items(i)) Then
lstVerktyg.SetItemChecked(i, True)
End If
Next