Error when I set a radio button to be checked by default - vb.net

I have a radio button in my VB.NET dll that I wan't to be checked by default. There is a total of 3 radio buttons in this group. Under its properties I set Checked = true. I verified the code was there, this is all the form generated code for the radio button:
Me.rdbProductPC.AutoSize = True
Me.rdbProductPC.Checked = True
Me.rdbProductPC.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdbProductPC.Location = New System.Drawing.Point(49, 12)
Me.rdbProductPC.Name = "rdbProductPC"
Me.rdbProductPC.Size = New System.Drawing.Size(45, 17)
Me.rdbProductPC.TabIndex = 1
Me.rdbProductPC.TabStop = True
Me.rdbProductPC.Text = "P&&C"
Me.rdbProductPC.UseVisualStyleBackColor = True
For some reason I get this error when I start the application:
An error occurred creating the form. See Exception.InnerException for details. The error is: ExecuteReader requires an open and available Connection. The connection's current state is closed.
Nothing has changed besides the one line adjusting the checked value. Any idea what could be causing this?
This is the code for my GetProducts() method. The error arises after the call to ExecuteReader() but I cannot see the code for this. If my g_strSQL = pc_mis_busunit_product_relate_summary it executes fine. But when g_strSQL = pc_mis_busunit_product_relate_summary '','','N' it errors out.
That being said, if I leave the radio button unchecked by default and then check it later while the program is running it will go into this same method and g_strSQL will look like pc_mis_busunit_product_relate_summary '','','N' and it will work fine.
Private Sub GetProducts(ByVal ProductList As ListBox)
Dim g_strSQL As String
ProductList.Items.Clear()
lstProductSel.Items.Clear()
lstProduct.Enabled = True
g_strSQL = String.Empty
objcmd.Connection = ControlConnection
'Clear location combo box
Select Case intProduct
Case Product.Summary
g_strSQL = g_strSQL & "pc_mis_busunit_product_relate_summary "
Case Product.Detail
g_strSQL = "SELECT DISTINCT b.dtl_prod_cd, rtrim(ltrim(b.dtl_prod_desc))"
g_strSQL = g_strSQL & " FROM product_detail_ref b "
g_strSQL = g_strSQL & " ORDER BY rtrim(ltrim(b.dtl_prod_desc)) "
Case Else
Exit Sub
End Select
If p_and_C <> String.Empty Then
g_strSQL = g_strSQL & "'" & String.Empty & "','" & String.Empty & "','" & p_and_C & "'"
End If
If g_strSQL <> "" Then
objcmd.CommandText = g_strSQL
rsProducts = objcmd.ExecuteReader()
End If
'Process results from query
If rsProducts.HasRows = False Then
rsProducts.Close()
Exit Sub
Else
' This nested if will check which radio button is selected and add the corresponding
' 'all' entry to the top of the lstProduct box
If rdbProductPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_P_AND_C)
ElseIf rdbProductNonPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_NON_P_AND_C)
Else
ProductList.Items.Add(PAndCConstants.ALL)
End If
ProductList.SelectedIndex = 0
While rsProducts.Read()
ProductList.Items.Add(rsProducts(0))
End While
ProductList.SetSelected(0, True)
rsProducts.Close()
End If
rsProducts = Nothing
End Sub

Related

Search data in DataGridView using FilterDataRow VB.Net

DV = New DataView(ds.Tables("CustomerList"))
FlxCustomerList.DataSource = ds.Tables("CustomerList").DefaultView
myDataTable = CType(FlxCustomerList.DataSource, DataView).ToTable
drToAdd = myDataTable.NewRow()
drToAdd("Customer Account") = ""
drToAdd("Customer Name") = ""
drToAdd("Customer Group") = ""
drToAdd("City") = ""
drToAdd("Mobile No") = ""
drToAdd("Status") = ""
myDataTable.Rows.InsertAt(drToAdd, 0)
myDataTable.AcceptChanges()
FlxCustomerList.DataSource = myDataTable.DefaultView
For Each dtrow As DataGridViewRow In FlxCustomerList.Rows
If dtrow.Index = 0 Then
dtrow.Frozen = True
Else
dtrow.ReadOnly = True
End If
Next
To achieve the search in Datagridview functionality, I'm getting the first row by this, on search enter, key-down function call this
CustomerAccountFilterStr = CStr(Me.DataGridView1.Rows(0).Cells("CustomerAccount").Value)
sStr = sStr & " [Customer Account] like '%" & CustomerAccountFilterStr & "%'"
ds.Tables("CustAcc").DefaultView.RowFilter = sStr
This is how I binding Data to DataGridView
myDataView.RowFilter = sStr
FlxCustomerList.DataSource = myDataView
And Then The DataGridView which is bound to the DefaultView of DataSet. I froze the first row but now, couldn't understand how to put back filtered values from the second-row onwards to the grid.
The example output should resemble like below.
I'm stuck to implement this functionality. please guide How to implement this functionality?

VB How to Clear existing items in listview

I am trying to search the information from the sql server then show at the listview. Everytime I click search it won't clear the existing records based on the past time searching. I've tried item.clear, it will only show me the new search but it won't clear all the existing records. Can someone help please?
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim strNameSource As String
Dim strPhoneSource As String
Dim strBothSource As String
If OpenConnect() = True Then
Try
If ChkCustName.Checked = True Then
strNameSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strNameSource)
ElseIf ChkPhoneNumber.Checked = True Then
strPhoneSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "'"
SearchReservation(strPhoneSource)
ElseIf ChkCustName.Checked = True And ChkPhoneNumber.Checked = True Then
strBothSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "' AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strBothSource)
End If
txtLastName.Clear()
txtPhoneNumber.Clear()
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End If
End Sub
Private Sub SearchReservation(ByVal strSource As String)
Dim itemcollection(100) As String
Dim Row As Integer
Dim Column As Integer
Dim ListViewItem As New ListViewItem
lstReservation.Items.Clear()
Try
cmd = New OleDb.OleDbCommand(strSource, cnn)
Adapter = New OleDb.OleDbDataAdapter(cmd)
Adapter.Fill(Ds, "Table")
'Now adding the Items in Listview
If Ds.Tables(0).Rows.Count = 0 Then
' Something went wrong. warn user
MessageBox.Show(Me, "Could not find the Customer", "Customer finding Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstReservation.BeginUpdate()
For Row = 0 To Ds.Tables(0).Rows.Count - 1
For Column = 0 To Ds.Tables(0).Columns.Count - 1
itemcollection(Column) = Ds.Tables(0).Rows(Row)(Column).ToString()
Next
ListViewItem = New ListViewItem(itemcollection)
lstReservation.Items.Add(ListViewItem)
Next
lstReservation.EndUpdate()
End If
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End Sub
Lots of issues with your code, but I'll focus on your immediate issue.
You keep filling the DataSet with new tables, but you keep using the original table that is still in position zero of the DataSet.
I would venture a guess that you need to clear the rows of your DataTable:
If Ds.Tables.Contains("Table") Then
Ds.Tables("Table").Rows.Clear()
End If
lstReservation.Items.Clear()
of just clear any tables there:
Ds.Tables.Clear()
lstReservation.Items.Clear()

Background Worker Not Clearing Resources

I'm currently working on an application that fetches some information from a database using a BW. It uses a stores number, referred to as IDP and searches the correct database. It works perfectly for my needs. However, each time it runs it's adding anywhere between 10-300 KBs to RAM, it is not releasing this memory once it completes. Since this code can be ran hundreds of times a day by numerous different people on a virtual machine with limited resources I really need it to release any memory it uses. Can anyone see where I'm going wrong?
Note: I'm self-taught and I'm doing this as more of a hobby that helps me out at work and not actually employed to do this, as I'm sure some of you will be happy to know once seeing my newbie code.
Public Sub KickoffStoreBrief() 'Called when txtIDP (text box) text changes
Dim args As BW_GetStoreBriefVariables = New BW_GetStoreBriefVariables()
args.Current_IDP = txtIDP.Text.Trim
If BW_GetStoreBrief.IsBusy Then
MsgBox("Worker busy!")
Else
BW_GetStoreBrief.RunWorkerAsync(args)
End If
End Sub
Private Sub BW_GetStoreBrief_DoWork(sender As Object, e As DoWorkEventArgs) Handles BW_GetStoreBrief.DoWork
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Argument, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
Using DatabaseConnection As New SqlConnection(args.ConnectionString)
Dim command As New SqlCommand(SQL CODE IS HERE, DatabaseConnection)
command.CommandTimeout = 20
'Attempt to open the connection
command.Connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
Dim dt As New DataTable()
dt.Load(reader)
reader = Nothing
'Check if returned anything
If dt.Rows.Item(0).Item(0) = Nothing Or dt.Rows.Item(0).Item(0).ToString = "False" Or dt.Rows.Item(0).Item(0).ToString = "" Then
'Branch not found.
GoTo Ender
End If
'Prefix 0's infront of the IDP as required
Dim CompleteIDPNumber As String = ""
If dt.Rows.Item(0).Item(0).ToString.Length < 4 Then
If dt.Rows.Item(0).Item(0).ToString.Length = 2 Then
CompleteIDPNumber = "00" & dt.Rows.Item(0).Item(0).ToString
ElseIf dt.Rows.Item(0).Item(0).ToString.Length = 3 Then
CompleteIDPNumber = "0" & dt.Rows.Item(0).Item(0).ToString
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
'Populate strings
Dim StoreName As String = CompleteIDPNumber & " - " & dt.Rows.Item(0).Item(1).ToString.Trim
Dim UISupports As Integer = 20 'This is the amount of characters that will fit in label space
If StoreName.Length > UISupports Then
StoreName = StoreName.Substring(0, UISupports).ToString.Trim & "..." & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
Else
StoreName = StoreName & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
End If
args.Brief_StoreName = StoreName
StoreName = Nothing 'We no longer need this, release it from memory
UISupports = Nothing 'We no longer need this, release it from memory
CompleteIDPNumber = Nothing 'We no longer need this, release it from memory
If dt.Rows.Item(0).Item(2) = 0 Or dt.Rows.Item(0).Item(2).ToString.Trim = "0" Then
args.Brief_POSNumber = "IS"
Else
args.Brief_POSNumber = dt.Rows.Item(0).Item(2).ToString.Trim
End If
args.Brief_Category = dt.Rows.Item(0).Item(3).ToString 'CAT
args.Brief_STCamera = dt.Rows.Item(0).Item(4).ToString 'Counter
args.Brief_Franch = dt.Rows.Item(0).Item(5).ToString
Ender:
e.Result = args
'Close connection
dt.Dispose()
command.Connection.Close()
command.Dispose()
End Using
End Sub
Private Sub BW_GetStoreBrief_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BW_GetStoreBrief.RunWorkerCompleted
If e.Error IsNot Nothing Then
ListBox1.Items.Insert(0, Now.ToString("HH:mm:ss") & " | Error | Unable to connect to store DB.")
lblNotFound.Text = "Unable to connect to database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Error.Message, 0)
ElseIf e.Cancelled Then
Else
' Access variables through args
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Result, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
If args.Brief_StoreName = "" Then
ListBox1.Items.Insert(0, Now.ToString("hh:mm:ss") & " | Notice | IDP " & args.Current_IDP & " not found in database.")
'show warning panel
lblNotFound.Text = "Store not found in database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
GoTo Ender
Else
'Store found update UI
lblBranchInfo_StoreName.Text = args.Brief_StoreName
lblBranchInfo_POSNumber.Text = args.Brief_POSNumber
lblBranchInfo_CameraType.Text = args.Brief_STCamera
Panel_NotFound.Visible = False
Panel_NotFound.SendToBack()
End If
args = Nothing
End If
Ender:
btnStoreDetails.Enabled = True
End Sub
As you can see i've tried to make sure I'm not leaving anything behind, but the memory keeps jumping up and doesn't go down. Overall we're talking about 35MBs being used when this codes been ran only a few times and nothing else is happening with the program/form. Because this is on a remote virtual machine the program can be open for days without being closed, and with the memory usage increasing each time it will become a very big issue. Any help would be appreciated.

Prevent ListView Row Disappearing Upon Data Update

I have a listview that displays message items. When the parent window is open, it starts a timer that checks every xx amount to see if any new messages have been sent. This then clears the listview control and rebuilds it everytime (not sure if this is the best way).
Anyway, if the mouse is sitting over the top of a listview item when the listview gets rebuilt, the listview row is blank. However, moving the mouse off the item and back on the item will redraw it fine.
The code to build my listview is such:
Private Sub LoadMessages()
Dim QueryString As String
Try
lsvMail.Items.Clear()
QueryString = "SELECT * FROM Mail WHERE recipient = '" & Current_User.DisplayName & "' ORDER BY sent DESC"
Dim ExQry As New MySqlCommand(QueryString, MySQLConn)
Dim da As New MySqlDataAdapter(ExQry)
da.Fill(dsMessages, "Messages")
Dim tempDT As DataTable = dsMessages.Tables("Messages")
If dsMessages.Tables.Count > 0 And dsMessages.Tables(0).Rows.Count > 0 Then
For x = 0 To (dsMessages.Tables(0).Rows.Count - 1)
Dim lvi As New ListViewItem(tempDT.Rows(x)("is_replied").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("sender").ToString)
If CBool(tempDT.Rows(x)("is_read")) = True Then
lvi.Font = RegularFont
Else
lvi.Font = BoldFont
End If
If CBool(tempDT.Rows(x)("is_followup")) = True Then
lvi.ForeColor = Color.Red
Else
lvi.ForeColor = Color.Black
End If
lvi.SubItems.Add(tempDT.Rows(x)("subject").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("sent").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("is_followup").ToString)
lvi.Name = tempDT.Rows(x)("id").ToString
lsvMail.Items.Add(lvi)
Next
End If
da = Nothing
tempDT = Nothing
dsMessages.Clear()
Catch ex As Exception
CreateLog("Module: LoadMailMessages()" & vbNewLine & "Exception Error: " & ex.Message)
MsgBox("Exception Error: " & ex.Message, MsgBoxStyle.Critical, "Module: LoadMailMessages()")
End Try
End Sub
Like mentioned, I have a timer event that simply calls the LoadMessages() routine.
I am trying to have a 'live' feed to the messages window so that new items will appear in the listview if the window is open.
Any help appreciated - thanks.
Try adding refresh:
Next
lvi.Refresh()
End If

Vb.net Journal Program Issue

Okay so for an internship project i'm making a Journal with streamwriters and streamreaders.
I have to to where you can create an account with a name, Username, and Password. I also have it to where it creates a txt file in that persons name when you create the account. Now, they login and it brings them to the journal page. The Journal Page for the most part has a Date for your journal Entry, the title of the journal and the journal entry text itself.
The problem that I am having is that when you click the button to create/edit a journal entry, it goes through a sub routine that checks if that journal exists (Meaning that there is already one for that date) or not. If it doesn't exist, then it should create a new one at the bottom of the text file. If it does exist then it should edit the lines in which that journal are stationed in the text file.
Code:
Private Sub CreateBtn_Click(sender As System.Object, e As System.EventArgs) Handles CreateBtn.Click
Errors = ""
Dim TempCounter As Integer = 0
If TitleTxt.Text = "" Then
Errors = "You must enter a title." & vbCrLf
End If
If JournalTextRtxt.Text = "" Then
Errors &= "You must enter an entry for the journal."
End If
If Errors <> "" Then
MessageBox.Show("There's an error in creating/editing your journal." & vbCrLf & "Error(s):" & vbCrLf & Errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(TempCounter).TheDate = JournalDate
arrJournalEntries(TempCounter).Title = JournalTitle
arrJournalEntries(TempCounter).JournalEntry = JournalText
CheckAndWrite()
End If
End Sub
Private Sub CheckAndWrite()
Dim Reader As New StreamReader(MyName & ".txt", False)
Dim Sline As String = Reader.ReadLine
Counter = 0
Do Until (Sline Is Nothing) 'Perform the code until the line in the text file is blank
If Not Sline Is Nothing Then 'If the line in the text file is NOT blank then
For i As Integer = 1 To 3
Select Case i
Case 1
arrJournalEntries(Counter).TheDate = Sline
Sline = Reader.ReadLine
Case 2
arrJournalEntries(Counter).Title = Sline
Sline = Reader.ReadLine
Case 3
arrJournalEntries(Counter).JournalEntry = Sline
Sline = Reader.ReadLine
End Select
Next
End If
JournalDate = arrJournalEntries(Counter).TheDate
Time = DateTimePicker1.Value
MsgBox("Journal Date = " & JournalDate & vbCrLf & "Today's Date = " & Time)
If Time = JournalDate Then
JournalFound = True
Else
Counter += 1
JournalFound = False
End If
Loop
Reader.Close()
Try
If Sline Is Nothing Or JournalFound = False Then
MsgBox("Your journal is now going to be created.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
If JournalFound = True Then
MsgBox("Your journal is now going to be edited.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured" & vbCrLf & vbCrLf & "Original Error:" & vbCrLf & ex.ToString)
End Try
End Sub`
The problem that's occuring is that it's not only writing in the first time wrong. When it's supposed to say it's going to edit, it doesn't, it just says creating. But it just adds on to the file. After pressing the button 3 times with the current date. and the Title being "Test title", and the journal entry text being "Test text". This is what occured.
It should just be
7/10/2012 3:52:08 PM
Test title
Test text
7/10/2012 3:52:08 PM
Test title
Test text
the whole way through. but of course if it's the same date then it just overwrites it. So can anybody please help me?
You are only filtering your array by the date, so it looks like you have an object with a date but no title or text:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
The "quick" fix:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
If arrJournalEntries(Counter).Title <> String.Empty Then
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
End If
Counter += 1
Loop
Do consider getting rid of the array and using a List(of JournalEntry) instead. Your code looks difficult to maintain in its current state.