Keep checked items checked while searching in CheckedListBox - vb.net

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

Related

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

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

Like statement in VB.NET

If I enter an input into the textbox, my listview updates, but there is always no result even though my input is there.
Private Sub searchRecord()
Dim dt As New DataTable
dt = ExecuteQuery("SELECT * FROM tblSupplier WHERE '" & cboSearch.Text
& "' LIKE '" & txtSearch.Text & "%'")
lvSupplier.Items.Clear()
If dt.Rows.Count > 0 Then
For ctr = 0 To dt.Rows.Count - 1
Dim item As New ListViewItem
item.Text = dt.Rows(ctr)("SuppID")
item.SubItems.Add(dt.Rows(ctr)("SuppName"))
item.SubItems.Add(dt.Rows(ctr)("SuppAddress"))
item.SubItems.Add(dt.Rows(ctr)("SuppConPerson"))
item.SubItems.Add(dt.Rows(ctr)("SuppConNumber"))
item.SubItems.Add(dt.Rows(ctr)("SuppEmail"))
lvSupplier.Items.Add(item)
Next
End If
End Sub
Dim dt As New DataTable
dt = ExecuteQuery("SELECT * FROM tblSupplier")
Try
If txtSearch.Text = "" Then
Call fillSupplier(dt, lvSupplier)
Else
Call searchRecord()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Your SQL statement should be like this...
"SELECT * FROM tblSupplier WHERE " & cboSearch.Text & " LIKE '%" & txtSearch.Text.Replace("'","''").Trim() & "%'"
This way you should be able to search for any character or word wherever it's placed in the original word or phrase found in the database.

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.

How do I populate my form using Listview

I've successfully taught myself how to pull some data from a MySQL database and bind it to a ListView control (ListViewCard).
Now I can't figure out how to use the SelectedIndexChanged event to inerate through the records and populate some other controls on my form (i.e, 7 textboxes, 2 comboboxes, and 2 datetimepickers).
Your help would be greatly appreciated. Here's my code:
Private Sub loadCard()
Try
'FOR MySQL DATABASE USE
'Dim dbQuery As String = ""
'Dim dbCmd As New MySqlCommand
'Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
Dim i As Integer
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE customer.accountNumber = '" & TextBoxAccount.Text & "'"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbTable)
End With
ListViewCard.Items.Clear()
For i = 0 To dbTable.Rows.Count - 1
With ListViewCard
.Items.Add(dbTable.Rows(i)("ccID"))
With .Items(.Items.Count - 1).SubItems
.Add(dbTable.Rows(i)("ccNumber"))
.Add(dbTable.Rows(i)("ccExpireMonth"))
.Add(dbTable.Rows(i)("ccExpireYear"))
End With
End With
Next
Catch ex As MySqlException
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
End Sub