Populate datagridview of another form VB.NET - vb.net

In an attempt to fix my previous problem, i tried to move Form2's(contacts) load event codes to form1's background worker...The code is :
Private Sub Contact_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Con.open
dim cmd as new sqlcommand("Select * from Users",con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
datagrid2.DataSource = table
con.Close()
datagrid2.Columns(0).Frozen = True
datagrid2.Columns(0).Width = 48
datagrid2.Columns(1).Width = 33
AddSelectAllCheckBox(datagrid2)
Dim img As DataGridViewImageColumn
img = datagrid2.Columns(1)
img.ImageLayout = DataGridViewImageCellLayout.Stretch
ExtensionMethods2.DoubleBuffered(datagrid2, True)
ExtensionMethods1.DoubleBuffered(Panel3, True)
ExtensionMethods1.DoubleBuffered(Panel9, True)
mymy1.DoubleBuffered(inpeople, True)
If datagrid2.Rows.Count <= 0 Then
added.Visible = True
Else
added.Visible = False
End If
Try
MetroComboBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\ct_list.ofptx"))
moneylist.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\cr_list.ofptx"))
ttlist.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\tt_list.ofptx"))
Catch ex As Exception
MsgBox("One or more files required by OffPo is missing/corrupted" & vbCrLf & "" & vbCrLf & "Error occured in : ct_list.ofptx or cr_list.ofptx")
End Try
entrylabel.Text = "There are/is " & datagrid2.Rows.Count & " contact entries"
svbtn.Enabled = False
upbtn.Enabled = False
dtb.Enabled = False
End Sub
To fix my previous problem(to fix the BACKGROUND WORKER FREEZING UI issue), i moved this code to the form1's BackGroundWorker's DoWork event. The code for RunCompleted event looks like this :
Private Sub BackgroundWorker2_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
Contact.Show()
waiting.Hide()
End Sub
The problem is, when BackGroundWorker shows the Form2(contacts), the datagridview becomes empty.It only loads the column names but no rows/data...What am i missing ?? Why isn't the dgvw populating ?
I didn't add the BackGroundWorker Do_work event's code as it is the same as Form2's load event code

Related

Textbox not refreshing

Dim VoucherOpenConnection As New OleDbConnection
' VoucherOpenConnection = New OleDbConnection
VoucherOpenConnection.ConnectionString = "My Connection String"
Dim VoucherString As String = "My Query"
Dim DAVoucherString As New OleDbDataAdapter(VoucherString, VoucherOpenConnection)
Dim DTVoucherString As New DataTable
DAVoucherString.Fill(DTVoucherString)
If DTVoucherString.Rows.Count <> 0 Then
cmbCategory.Text = DTVoucherString.Rows(0).Item(8).ToString
txtDetails.Text = DTVoucherString.Rows(0).Item(2).ToString
txtshop.Text = DTVoucherString.Rows(0).Item(3).ToString
txtAmount.Text = DTVoucherString.Rows(0).Item(4).ToString
txtRemarks.Text = DTVoucherString.Rows(0).Item(5).ToString
txtInvoiceNum.Text = DTVoucherString.Rows(0).Item(11).ToString
txtCashAmt.Text = DTVoucherString.Rows(0).Item(6).ToString
Me.Refresh()
Else
MsgBox("No valid record could be found(Cash)!!")
End If
I have the above code inside a sub procedure and call it from another form. When the sub is called the first time, all the textboxes display the correct values. But when I try again, the values do not update. Putting a breakpoint in the sub reveals that the code is working correctly as hovering the mouse over the textboxes shows the correct values.
I have already tried the following methods to no avail:
Me.Refresh
Me.Update
Textbox.update/refresh
This is in VB.NET 2019.
Edit:Code in the calling form:
Private Sub DGVTotalReport_CellMouseDoubleClick(sender As Object, e As
DataGridViewCellMouseEventArgs) Handles
DGVTotalReport.CellMouseDoubleClick
Dim ExpForm As New ExpenseEntry
My.Settings.TranCodeExpOpen =
DGVTotalReport.Rows(e.RowIndex).Cells(8).Value
If My.Settings.ExpenseForm = False Then
ExpForm.Show()
ExpForm.OpenVoucher()
My.Settings.ExpenseForm = True
Else
My.Settings.ExpenseForm = True
ExpForm.Activate()
ExpForm.OpenVoucher()
ExpForm.Refresh()
End If
End Sub

Winforms custom loading screen text not loading

I'm using VB.NET winforms and have a particular form that take a while to load up so I've decided to implement a loading screen to make it feel a bit less freezey. Here is the code I'm using in my freezey form load.
Private Sub HanleyView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim loaderForm As New Loader
loaderForm.Show()
AllOpenOrdersList.FullRowSelect = True
NeedsAttentionList.FullRowSelect = True
StockManagementList.FullRowSelect = True
Dim lowStockCount = HelperMethods.ReviewLowStock()
ReviewLowStockButton.Text = "Review Low Stock (" & lowStockCount & ")"
RefreshAllOpenOrdersList()
RefreshNeedsAttentionList()
RefreshStockManagementList()
loaderForm.Close()
End Sub
So I start by showing the loading form and finish by closing it.
The good new is that the loading form appears, but the bad news is the "LOADING..." text which is a label on my loading form doesn't show, I just get a white patch there instead. I've tried two approaches, the above and calling Loader.Show and Loader.Close. I've also tried setting loaderForm.Label1.Text = "LOADING..." but this didn't make any difference. Each time the form loads (and the title loads which says "Loading please wait") but not the label on the form itself.
I've now also tried:
Dim loaderForm As New Loader
Dim lbl As New Label
loaderForm.Controls.Add(lbl)
lbl.Text = "LOADING..."
lbl.Location = New System.Drawing.Point(42, 21)
loaderForm.Show()
AllOpenOrdersList.FullRowSelect = True
NeedsAttentionList.FullRowSelect = True
StockManagementList.FullRowSelect = True
Dim lowStockCount = HelperMethods.ReviewLowStock()
ReviewLowStockButton.Text = "Review Low Stock (" & lowStockCount & ")"
RefreshAllOpenOrdersList()
RefreshNeedsAttentionList()
RefreshStockManagementList()
loaderForm.Close()
But this hasn't worked either.
EDIT: I've tried Varocarbas' code but was still unsuccessful. The form loads but the text remains a white patch
Dim loaderForm As Form = New Form
With loaderForm
.Height = 200
.Width = 300
.Location = New System.Drawing.Point(12, 12)
End With
Dim label1 As Label = New Label
loaderForm.Controls.Add(label1)
With label1
.Text = "LOADING..."
.Location = New System.Drawing.Point(12, 45)
End With
loaderForm.Show()
EDIT 2: For clarity, here is my code now it is working using Franck suggestion
Private Sub HanleyView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim loaderForm As New Loader
loaderForm.Show()
Application.DoEvents()
AllOpenOrdersList.FullRowSelect = True
NeedsAttentionList.FullRowSelect = True
StockManagementList.FullRowSelect = True
Dim lowStockCount = HelperMethods.ReviewLowStock()
ReviewLowStockButton.Text = "Review Low Stock (" & lowStockCount & ")"
RefreshAllOpenOrdersList()
RefreshNeedsAttentionList()
RefreshStockManagementList()
loaderForm.Close()
End Sub
I have kept my original code and simply added Application.DoEvents() below loaderform.Show and it works properly now.
Also the below screenshot is what I mean by using the designer (and not doing it programmtically):
Multithreading!
Create and run the loaderForm on a separate thread. But then you need to be careful about cross-thread operations, so have a self-invoking method on your loaderForm, such as:
Public Sub ParseStatus(msg as String)
If Me.InvokeRequired Then Me.Invoke(New Action(Of String)(AddressOf Me.ParseStatus), msg) Else Me.Label1.Text = msg
End Sub
Also in your loaderForm you want something like:
Public Sub Finish()
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Then in the Load procedure of your form:
Private Sub HanleyView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim loaderForm As New Loader
Dim loaderThread As New Threading.Thread(New Threading.ThreadStart(AddressOf loaderForm.ShowDialog))
loaderThread.Start()
loaderForm.ParseStatus("Loading ...")
AllOpenOrdersList.FullRowSelect = True
NeedsAttentionList.FullRowSelect = True
StockManagementList.FullRowSelect = True
Dim lowStockCount = HelperMethods.ReviewLowStock()
ReviewLowStockButton.Text = "Review Low Stock (" & lowStockCount & ")"
LoaderForm.ParseStatus("Refreshing open orders ...")
RefreshAllOpenOrdersList()
loaderForm.ParseStatus("Refreshing needs attentions?") ' etc
RefreshNeedsAttentionList()
RefreshStockManagementList()
loaderForm.Finish()
End Sub
But Visual Studio has a neat thing called SplashScreen in its project templates for VB.NET. I'd use that one, if you aren't already…
Edit: I corrected the syntax errors in the code.

VB.net ListView Adding Items Multiple Times

I am having an issue where I get multiple entries in my ListView for the same item if I run my action more than once.
I am creating a simple network scanner/hostname grabber that will add the items to the listview as they come back alive to my ping test.
When I run it the first time it runs fine and creates one entry as it should.
When I run it subsequent times it creates the item as many times as I have ran the code ex. 3rd time hitting start it creates each entry 3 times when it should just create the entry once.
Here is my go button code:
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
Dim verifyIP
ListView1.Items.Clear()
chkDone = 0
verifyIP = ipChk(ipAdd.Text)
If verifyIP = 1 Then
ipAddy = Split(ipAdd.Text, ".")
pingTest1.WorkerReportsProgress = True
pingTest1.WorkerSupportsCancellation = False
AddHandler pingTest1.ProgressChanged, AddressOf pingTest1_ProgressChanged
pingTest1.RunWorkerAsync()
pingTest2.WorkerReportsProgress = True
pingTest2.WorkerSupportsCancellation = False
AddHandler pingTest2.ProgressChanged, AddressOf pingTest2_ProgressChanged
pingTest2.RunWorkerAsync()
pingTest3.WorkerReportsProgress = True
pingTest3.WorkerSupportsCancellation = False
AddHandler pingTest3.ProgressChanged, AddressOf pingTest3_ProgressChanged
pingTest3.RunWorkerAsync()
pingTest4.WorkerReportsProgress = True
pingTest4.WorkerSupportsCancellation = False
AddHandler pingTest4.ProgressChanged, AddressOf pingTest4_ProgressChanged
pingTest4.RunWorkerAsync()
While chkDone < 4
wait(25)
End While
Else
MsgBox("IP Invalid")
End If
MsgBox("Done")
End Sub
Here is the code from one of the background workers I am using:
Private WithEvents pingTest1 As BackgroundWorker = New BackgroundWorker
Private Sub pingTest1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles pingTest1.DoWork
Try
Dim hostCheck
pingResult1 = 0
pingTestDone1 = 0
tryIP1 = ipAddy(0) & "." & ipAddy(1) & "." & ipAddy(2) & ".1"
If My.Computer.Network.Ping(tryIP1) = True Then
'Dim pingsender As New Net.NetworkInformation.Ping
'If pingsender.Send(tryIP).Status = Net.NetworkInformation.IPStatus.Success Then
Try
'Dim host As System.Net.IPHostEntry
hostCheck = ""
'host = System.Net.Dns.GetHostByAddress(tryIP3)
'MsgBox(host.HostName)
'host3 = host.HostName
'hostCheck = System.Net.Dns.GetHostEntry(tryIP3).HostName
hostCheck = System.Net.Dns.GetHostByAddress(tryIP1)
'get the hostname property
hostCheck = hostCheck.HostName
pingTest1.ReportProgress("1", hostCheck)
Catch f As Exception
'MsgBox("Error: " & f.Message)
pingTest1.ReportProgress("1", "No Hostname Found")
End Try
Else
pingResult1 = 2
End If
Catch d As Exception
MsgBox("There was an error trying to ping the IP Address: " & d.Message)
End Try
End Sub
Private Sub pingTest1_ProgressChanged(e.ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
MsgBox("Hey")
Dim str(2) As String
Dim itm As ListViewItem
str(0) = tryIP1 & " Is Alive!!!"
str(1) = e.UserState
itm = New ListViewItem(str)
ListView1.Items.Add(itm)
str(0) = ""
str(1) = ""
itm = Nothing
End Sub
Private Sub pingTest1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles pingTest1.RunWorkerCompleted
chkDone = chkDone + 1
End Sub
I added the Hey box and sure enough the ProgressChanged event gets triggered the amount of times I have hit the Go button. Is it something I have coded incorrectly?
It's most likely because you're adding, but not removing your handlers for the progress changed, so you're handling the event multiple times.
Try adding your Progress Changed Event Handlers when you're instantiating your Background workers, rather than every time you click your button. This way they will only handled once.

Send value to parent then close child form, on event

I have a parent form with a combobox populated from a database, from which the user can select. The last value in the combo box is "add new", if the user selects this, a child form opens for the user to add a new value to the database. I have a button press event to add this value to the database, send the new return value to the parent and close the form. The parent should then select the new value from it's combo box and wait for the user to perform another action.
However, the code to send the return value to parent and close the form isn't working correctly. I hide the child, then call a function on it with the parent to access the return value. At this point the child form shows and the code stops before it runs another hide or close.
How can I fix this (code below)?
Parent Combobox event:
Private Sub cmbLocations_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbLocations.SelectedIndexChanged
If Not cmbLocations.SelectedIndex = -1 Then
If cmbLocations.SelectedIndex = cmbLocations.Items.Count - 1 Then
If diaAddLocation.IsAccessible = False Then diaAddLocation.Activate()
diaAddLocation.RequestSender = Me
diaAddLocation.ShowDialog()
FillLocations()
cmbLocations.SelectedIndex = LocationFromLocationName(diaAddLocation.formresult)
diaAddLocation.Close()
diaAddLocation.Dispose()
Else
bttYes.Enabled = True
End If
End If
End Sub
Child Button Press and Return value function
Public Sub bttAddLOCtoDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttAddLOCtoDatabase.Click
Dim LocationToBeAdded As String
LocationToBeAdded = "'" & TextBox1.Text & "'"
AddLocation("'" & textbox1.Text & "'")
FormResult = textbox1.Text
GetLocations()
frmFieldMaster.InitialiseNewParameter()
Me.Hide()
End Sub
Public Function Result() As String
Return FormResult
End Function
EDIT:
code with Steve's solution implemented:
Public Sub bttAddLOCtoDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttAddLOCtoDatabase.Click
Dim LocationToBeAdded As String
LocationToBeAdded = "'" & TextBox1.Text & "'"
AddLocation("'" & textbox1.Text & "'")
FormResult = textbox1.Text
GetLocations()
frmFieldMaster.InitialiseNewParameter()
DialogResult = Windows.Forms.DialogResult.OK
'me.Hide()
End Sub
Public Function Result() As String
Return FormResult
Me.Close()
End Function
Private Sub cmbLocations_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbLocations.SelectedIndexChanged
Dim ValueTaken As Boolean = False
If Not cmbLocations.SelectedIndex = -1 Then
If cmbLocations.SelectedIndex = cmbLocations.Items.Count - 1 Then
Using diaaddlocation = New diaAddLocation
diaaddlocation.requestsender = Me
If DialogResult.OK = diaaddlocation.showdialog Then
FillLocations()
cmbLocations.SelectedIndex = LocationFromLocationName(diaaddlocation.result)
diaaddlocation.close()
ElseIf DialogResult.Cancel = diaaddlocation.showdialog Then
cmbLocations.SelectedIndex = -1
End If
End Using
Else
bttYes.Enabled = True
End If
End If
End Sub
When I run the code it enters IF DialogResult.OK... and opens the child. Then when I close the child the parent runs the next two lines of code and get the result from the child. After this the parent runs the line IF DialogResult.OK... again and stops with the child open. The code never reaches the diaaddlocation.close line.
You don't need all of this. You could try something like this
If cmbLocations.SelectedIndex = cmbLocations.Items.Count - 1 Then
Using diaAddLocation = new diaAddLocation()
diaAddLocation.RequestSender = Me
if DialogResult.OK = diaAddLocation.ShowDialog() then
FillLocations()
cmbLocations.SelectedIndex = LocationFromLocationName(diaAddLocation.formresult)
End If
End Using
Else
.....
This requires the DialogResult property for bttAddLOCtoDatabase set to DialogResult.OK and the child form AcceptButton property set to bttAddLOCtoDatabase. Now you could remove the Hide() call inside the bttAddLOCtoDatabase_Click method
This works because, until you don't exit the Using statement, your child form is still available to read its properties (results)
EDIT: Not related to the main problem, but these lines are wrong:
ElseIf DialogResult.Cancel = diaaddlocation.showdialog Then
cmbLocations.SelectedIndex = -1
you should go with
Using diaAddLocation = new diaAddLocation()
diaAddLocation.RequestSender = Me
Dim dr = diaAddLocation.ShowDialog()
if dr = DialogResult.OK then
....
else if dr = DialogResult.Cancel then
....
end if
I don’t understand what is issue but if you are not getting value of “FormResult”
It doesn’t matter if you close from but it will be better to set DialogResult before closing it, cause you are showing it as dialog (showdialog)
Verify that diaAddLocation is instance of you window not the window class directly
If name of you form is frmdiaAddLocation then do not use it like
frmdiaAddLocation.showdialog
use it like
Dim diaAddLocation AS frmdiaAddLocation = New frmdiaAddLocation()
diaAddLocation.ShowDialog()
only using like this way will provide you result value

how to change selected option of textbox based on datareader result vb

.hi everyone I have this code:
Private Sub EditPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'InventorySysDataSet.tb_master_products' table. You can move, or remove it, as needed.
Me.Tb_master_productsTableAdapter.Fill(Me.InventorySysDataSet.tb_master_products)
sqlCnn = New SqlConnection("Data Source=ZEREY\SQLEXPRESS2008;Initial Catalog=InventorySys;Integrated Security=SSPI")
Me.txtRowId.Text = Form1.txtRowId.Text
'MsgBox(Me.txtRowId.Text)
sql = "Select * from tb_master_inventory_per_day where Inventory_Date = " & txtRowId.Text & ""
Dim upcmd As New SqlCommand("Select * from tb_master_inventory_per_day where Row_Id = #Row_Id", sqlCnn)
upcmd.Parameters.Add(New SqlParameter("#Row_Id", Me.txtRowId.Text))
upcmd.Connection.Open()
Try
Dim dr As SqlDataReader = upcmd.ExecuteReader()
If dr.Read Then
txtInventoryDate.Text = dr.Item("Inventory_Date")
cboProductCode.DisplayMember = dr.Item("Product_Code")
txtQty.Text = dr.Item("Product_Count")
Else
MessageBox.Show("Error!")
End If
Catch ex As SqlException
If ex.Number <> 0 Then
'ErrorProvider1.SetError(Me.txtuseridprofile, "Login Id: " &
'Me.txtuseridprofile.Text & " :Not Found!")
upcmd.Connection.Close()
Exit Sub
End If
End Try
upcmd.Connection.Close()
End Sub
what i want to do is to automatically change the selected option of the cboProductCode on page load depending on the result of a query executed onload also.
help pls! TIA!
.Haha! it's funny that i have tried so many ways but not tried using cboProductCode.Text instead of cboProductCode.DisplayMember. It now works! :D