VB .NET Socket Programing - vb.net

I have a tools build in VB .Net and use Socket Programing. If just use 1 Server my code already work but when I wanna user 2 server and connect from 1 server my tools can't be handle that problem.
I wanna 1 Client can connect to 2 server
My code like this
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports Pabertiyan
Public Class Form1
Dim Client As TcpClient
Dim Client2 As TcpClient
Dim sWrinteras As StreamWriter
'Dim NickFrefix As Integer = New Random().Next(1111, 9999)
Dim Pabertiyan As New Pabertiyan.Pabertiyan
Delegate Sub _xUpdate(ByVal str As String)
Sub xUpdate(ByVal str As String)
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), str)
Else
MsgBox("Sum of word in server is : " & str)
'TextBox1.AppendText(str & vbNewLine)
End If
End Sub
Sub Read(ByVal str As IAsyncResult)
Try
xUpdate(New StreamReader(Client.GetStream).ReadLine)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
Catch ex As Exception
xUpdate("Disconnect From Server")
Exit Sub
End Try
End Sub
Private Sub Send(ByVal str As String)
Try
sWrinteras = New StreamWriter(Client.GetStream)
sWrinteras.WriteLine(str)
sWrinteras.Flush()
Catch ex As Exception
MsgBox("You not Connect to Server")
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Button1.Text = "Connect" Then
Try
Client = New TcpClient(Pabertiyan.GetIPServer, Pabertiyan.GetPortServer)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf Read), Nothing)
Button1.Text = "Disconnect"
TextBox3.BackColor = Color.Lime
Catch ex As Exception
MsgBox("Server is Offline. Please Try Again Later!!!")
End Try
Else
Client.Client.Close()
Client = Nothing
Button1.Text = "Connect"
TextBox3.BackColor = Color.Red
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Send(TextBox5.Text)
End Sub
Private Sub CheckConfig_Tick(sender As Object, e As EventArgs) Handles CheckConfig.Tick
If Pabertiyan.ReloadConfig = 1 Then
Button4.Enabled = True
TextBox6.Text = Pabertiyan.ReloadConfig
End If
If Pabertiyan.ReloadConfig = 0 Then
Button4.Enabled = False
TextBox6.Text = Pabertiyan.ReloadConfig
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox5.Text = Pabertiyan.SearchChar
TextBox2.Text = Pabertiyan.TotalServer
TextBox7.Text = Pabertiyan.ModuleLogs
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
TextBox7.Text = Pabertiyan.ReloadConfig
TextBox5.Text = Pabertiyan.SearchChar
End Sub
End Class
Anyone can help me to solve my problem?

Related

How can I close the PrintPreviewDialog once the printing is complete?

As a new programmer in VB, I struggled to get my print routine working. Searching through a number of sources I developed the hybrid below which is working to print a simple .txt file. My question sounds like a simple one but I've learned nothing is simple in printing. How do I get the PrintPreviewDialog to close once the printing is complete?
Private Sub BtnPrint_Click(sender As Object, e As EventArgs) Handles BtnPrint.Click
Try
PrintPreviewDialog1.Document = PrintDocument1
PageSetupDialog1.PageSettings =
PrintDocument1.DefaultPageSettings
If PageSetupDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDocument1.DefaultPageSettings =
PageSetupDialog1.PageSettings
PrintPreviewDialog1.Size = New System.Drawing.Size(500, 600)
PrintPreviewDialog1.ShowDialog()
End If
Catch ex As Exception
MessageBox.Show("Printing Operation Failed" & vbCrLf &
ex.Message)
End Try
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Static MyNewAcctFile As String = IO.File.ReadAllText(strErrorFile)
Dim printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(MyNewAcctFile, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(MyNewAcctFile, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
MyNewAcctFile = MyNewAcctFile.Substring(charsFitted)
If MyNewAcctFile <> "" Then
e.HasMorePages = True
Else
e.HasMorePages = False
MyNewAcctFile = IO.File.ReadAllText(strErrorFile)
End If
End Sub
I would expect to see something more like:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
Private FileName As String
Private txtFileContents As String
Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
FileName = "C:\Users\mikes\Documents\SomeFile.txt"
txtFileContents = IO.File.ReadAllText(FileName)
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
If txtFileContents.Length > 0 Then
Using printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(txtFileContents, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(txtFileContents, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
txtFileContents = txtFileContents.Substring(charsFitted)
e.HasMorePages = (txtFileContents.Length > 0)
End Using
End If
End Sub
Private Sub PrintDocument1_EndPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.EndPrint
If Not PrintDocument1.PrintController.IsPreview Then
PrintPreviewDialog1.Close()
End If
End Sub
End Class

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

Reciving data from Cell counter through rs232

I have a cell counter machine that sends data automatically after test end through a rs232 cable. I tried the following code to receive that data but I get nothing although I changed the BaudRate value many times. What is the problem?
My code:
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class ComReadWrite
Dim myPorts As Array
Dim txtline As String
Dim txtchar As String
Dim txtbyte As String
Dim txtexisting As String
Delegate Sub setTextCallBack(ByVal txt As String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myPorts = IO.Ports.SerialPort.GetPortNames()
portnamecombo.Items.AddRange(myPorts)
WriteButton.Enabled = False
CloseButton.Enabled = False
BaudRateBox.Items.Add(110)
BaudRateBox.Items.Add(300)
BaudRateBox.Items.Add(600)
BaudRateBox.Items.Add(1200)
BaudRateBox.Items.Add(2400)
BaudRateBox.Items.Add(4800)
BaudRateBox.Items.Add(9600) 'Populate the baudratebox Combo box to common baud rates used
BaudRateBox.Items.Add(14400)
BaudRateBox.Items.Add(19200)
BaudRateBox.Items.Add(38400)
BaudRateBox.Items.Add(57600)
BaudRateBox.Items.Add(115200)
BaudRateBox.Items.Add(128000)
BaudRateBox.Items.Add(256000)
BaudRateBox.Text = 38400
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
SerialPort1.PortName = portnamecombo.Text
SerialPort1.BaudRate = BaudRateBox.Text
SerialPort1.ReadTimeout = 500
SerialPort1.Parity = Parity.None
SerialPort1.DataBits = 8
SerialPort1.StopBits = StopBits.One
SerialPort1.Open()
Start.Enabled = False
WriteButton.Enabled = True
CloseButton.Enabled = True
End Sub
Private Sub WriteButton_Click(sender As Object, e As EventArgs) Handles WriteButton.Click
SerialPort1.Write(Chr(6))
End Sub
Private Sub CloseButton_Click(sender As Object, e As EventArgs) Handles CloseButton.Click
SerialPort1.Close()
Start.Enabled = True
WriteButton.Enabled = False
CloseButton.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Try
RecievedText(SerialPort1.ReadExisting())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub RecievedText(ByVal txt As String)
If Me.ReadBox.InvokeRequired Then
Dim x As New setTextCallBack(AddressOf RecievedText)
Me.Invoke(x, New Object() {(txt)})
Else
Me.ReadBox.Text &= txt
End If
End Sub
End Class

How to update an Access DB from a DataGridView in Visual Basic

I am creating an inventory application which runs off of an Access DB in visual studio, using visual basic. I can populate my data grid view just fine, but when I try to add new information into the data grid view, it does not number correctly and it does not append my database.
I have tried binding and updating using the table adapter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Here is my code:
Public Class Form1
Private Sub enterbtn_Click(sender As Object, e As EventArgs) Handles enterbtn.Click
If username.Text = "Tanner" And password.Text = "bmis365" Then
GroupBox1.Visible = False
Else
MsgBox("Incorrect Username or Password, please try again.")
username.Clear()
password.Clear()
username.Focus()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.CurrentCell = Nothing
'This line of code loads data into the 'Database1DataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is where my new info is to be appended into the database, once the button is clicked.
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
'The Following Code is from https://social.msdn.microsoft.com/Forums/vstudio/en-US/36c54726-4f49-4e15-9597-7b201ec13ae7/search-in-datagrid-using-textbox-vbnet-without-data-connectivity?forum=vbgeneral
For Each row As DataGridViewRow In DataGridView2.Rows
For Each cell As DataGridViewCell In row.Cells
If Not IsNothing(cell.Value) Then
If cell.Value.ToString.StartsWith(searchbar.Text, StringComparison.InvariantCultureIgnoreCase) Then
cell.Selected = True
DataGridView2.CurrentCell = DataGridView2.SelectedCells(0)
End If
End If
Next
Next
End Sub
End Class
My output initially has 3 rows(numbered 1, 2, and 3) but any that are added through the application have the numbers -1, -2, -3 and so on. Also, when I close the program and restart it, my original rows (1, 2, and 3) are still there from when I entered them in the DB file, but any that were added through my application are gone.
Here is one way to do an Update, as well as a few other common SQL manipulations/operations.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

How can I make a Window Form return value of selected button

I am making a graphical representation of a movie cinema room on a windows form. Each seat is represented as a button.
I have another button on another form that is used to book a seat. This button initiates the cinema room form and if the user clicks on any button, the text on that button should be returned and displayed.
The Cinema room class (Graphical Representation)
Imports System.Data.SqlClient
Public Class Cinema1Seats
Dim seat As String = vbNull
Private Sub Cinema1Seats_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
con = getconnect()
con.Open()
Dim comm As New SqlClient.SqlCommand
comm = New System.Data.SqlClient.SqlCommand("select * from seats ", con)
' comm.Parameters.Add("#id", SqlDbType.VarChar).Value = ticketNumber
Dim sqlReader As System.Data.SqlClient.SqlDataReader
sqlReader = comm.ExecuteReader
Do While sqlReader.Read
Dim seat As String = sqlReader.GetString(0)
Dim seatbtn As New Button
seatbtn.Width = 50
seatbtn.Height = 20
seatbtn.Text = seat
AddHandler seatbtn.Click, AddressOf Me.Button_Click ' Again from answer by Reed.
Me.FlowLayoutPanel1.Controls.Add(seatbtn)
Loop
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim asas As String = (CType(sender, System.Windows.Forms.Button).Text)
MsgBox(asas)
End Sub
Public Function getseat() As String
If (seat = vbNull) Then
Else
Return seat
Me.Close()
End If
End Function
End Class
The Second form which has the button
Public Class SampleSeat_vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim flag As Integer = 0
Dim i As Integer = 0
While i < Application.OpenForms.Count And flag = 0
If Application.OpenForms(i).Name = "Cinema1Seats" Then
flag = 1
End If
i += 1
End While
If flag Then
Application.OpenForms("Cinema1Seats").BringToFront()
Else
Dim str As New Cinema1Seats
str.Show()
Dim we As String = str.getseat
MsgBox("You selected : " + we)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SampleSeat_vb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
It is not enitrely clear to me what you are trying to achieve but in order to find the text of the button that was clicked you can do something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim btn As Button = CType(sender, Button)
MessageBox.Show("You clicked on " + btn.Text")
End Sub