Currently in the process of "self teaching" visual basic so apologies for the basic question
Maybe I am going about this the wrong way but I want to use btnTA_StartLog to create a file and activate Timer1 to log data in a specified interval. Problem being outlog is only defined in btnTA_startLog and not in the other 2 subs. How can I make the recently declared outlog public and accessible to the other subs?
Public Sub btnTA_StartLog_Click(sender As Object, e As EventArgs) Handles btnTA_StartLog.Click
Dim file As String = GetFileName(False, "csv", "Data Output")
Dim outlog As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(file, True)
Timer1.Start()
btnTA_StartLog.Enabled = False
btbTA_LoggingStop.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
outlog.WriteLine(CStr(DateTime.Now) & "," & CStr(txbTA_Delivered_ml.Text) & "," & CStr(MyTC.Data.Temperature))
End Sub
Private Sub btbTA_LoggingStop_Click(sender As Object, e As EventArgs) Handles btbTA_LoggingStop.Click
Timer1.Stop()
outlog.Close()
End Sub
It has to be at the class level one way or another.
Private outlog As IO.StreamWriter
Public Sub btnTA_StartLog_Click(sender As Object, e As EventArgs) Handles btnTA_StartLog.Click
Dim file As String = GetFileName(False, "csv", "Data Output")
outlog = My.Computer.FileSystem.OpenTextFileWriter(file, True)
Timer1.Start()
btnTA_StartLog.Enabled = False
btbTA_LoggingStop.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
outlog.WriteLine(CStr(DateTime.Now) & "," & CStr(txbTA_Delivered_ml.Text) & "," & CStr(MyTC.Data.Temperature))
End Sub
Private Sub btbTA_LoggingStop_Click(sender As Object, e As EventArgs) Handles btbTA_LoggingStop.Click
Timer1.Stop()
outlog.Close()
End Sub
I used a private field, but it could be a private property. It could be contained in another object for which you have class level reference to.
not a vb.net person so I dont know the exact syntax but the rules are the same for c# which I do know.
Define outlog at the form level, ie outside any functions, in that way all functions can use it.
Related
I am trying to create an app that produces an excel document based on user input. The document can become quite extensive (multiple sheets), so I want to put the creation of the document on a BackgroundWorker and pass the progress to a ProgressBar.
I'm having problems accessing UI controls while creating the document.
How can I access multiple UI controls from a BackgroundWorker?
This is a very basic example of two of the many things that i want to do in the BackgroundWorker:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
OpenWorkbook()
Dim Combobox() As ComboBox = {ComboBox1, ComboBox2, ComboBox3, ComboBox4}
With xlWorkBook.Sheets("Cover1")
.Range("E5").Value = TextBox1.Text
.Range("E6").Value = TextBox2.Text
.Range("E7").Value = TextBox3.Text
.Range("E8").Value = TextBox4.Text
For i = 0 To Combobox.Count - 1
.Range("A" & i + 1).Value = Combobox(i).Text
Next
End With
CloseWorkBook()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
I'm not experienced at all and after researching on this subject, I'm still not getting along with the Delegate/Invoke. Any help would be awesome. Thanks in advance.
As pointed out by Heinzi you cant just pass reference to a control into a bgw. instead you pass the values.
Option Strict On
Public Class FormControls
WithEvents Bgw As New ComponentModel.BackgroundWorker With {.WorkerReportsProgress = True}
Public Class BgwArgs
Public TxtBx1Txt As String = FormControls.TextBox1.Text
Public TxtBx2Txt As String = FormControls.TextBox2.Text
Public CmbBx1Txt As String = FormControls.ComboBox1.SelectedText
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim BgwArgs As New BgwArgs
Bgw.RunWorkerAsync(BgwArgs)
End Sub
Private Sub Bgw_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles Bgw.DoWork
Dim BgwArgs As BgwArgs = DirectCast(e.Argument, BgwArgs)
.Range("E5").Value = BgwArgs.TxtBx1Txt 'etc
End Sub
End Class
I assume the OpenWorkbook is a sub that uses interop to create xlWorkBook where you would instead want to do that within the thread also, same with CloseWorkbook all that should be handled in the DoWork event and not in their own separate routines.
I have orders in text files in the debug folder and when i type the name of the order in a text box it displays the order is a list box and there is a combo box underneath where i can change the status of the meal preparation (Being prepared, ready to deliver etc,). If i go back to that form and type in the same order name into the textbox i need to previous prepartion status to be already in the textbox. Thanks for any help!
Public Class frmOrderStatus
Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click
Dim sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
lstOrder.Items.Add(sr.ReadLine)
Loop
End Sub
Private Sub OrderStatus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstOrder.Items.Clear()
btnStatus.Enabled = False
ChangeStatus.Enabled = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
strTxtOrderNum = txtOrderNum2.Text
btnStatus.Enabled = True
ChangeStatus.Enabled = True
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
strSaveStatus = ChangeStatus.SelectedIndex
End Sub
Private Sub ChangeStatus_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ChangeStatus.SelectedIndexChanged
End Sub
End Class
It recognizes the file; it just tells you it is in use. A Stream must be closed and disposed. I don't see the StreamReader even being closed let alone disposed. A `Using...End Using block will close and dispose of objects even if there is an error.
I just used a text file I happened to have to test.
Private strTxtOrderNum As String = "host"
Private Sub ReadFile()
Using sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
ListBox1.Items.Add(sr.ReadLine)
Loop
End Using
End Sub
Private Sub WriteFile()
Dim strSelectedItem = ComboBox1.Text
Using swVar As IO.StreamWriter = IO.File.AppendText(strTxtOrderNum & ".txt")
swVar.WriteLine(strSelectedItem)
End Using
End Sub
First, let's have a look at my code:
Private Sub FormLoad(sender As Object, e As EventArgs) Handles MyBase.Load
txtMDF.Text = My.Settings.MDF
End Sub
Assume My.Settings.MDF has a string value of Application.StartupPath + "\MyDB.mdf". I get this result:
But I want the result to be:
I have tried the following links and methods:
How to convert string to code in vb.net and to view static or public variables of main project
CodeDom - But didn't understand it.
As ProGamer Suggested,
First
save you My.Settings.MDF String = None
Second
Edit your code as follows:
Private Sub FormLoad(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.MDF = "None" Then
txtMDF.Text = Application.StartupPath + "\MyDB.mdf"
Else
txtMDF.Text = My.Settings.MDF
End If
txtMDF.Text = My.Settings.MDF
End Sub
Third
Add the following code to YourFormClose_Event
Private Sub FormClosing(sender As Object, e As CancelEventArgs) Handles Me.Closing
My.Settings.MDF = txtMDF.Text
My.Settings.Save()
End Sub
And NOTE that you should select "User" from 'Scope Drop Down' in the Settings for MDF instead of "Application" or else My.Settings.Save() will not work and it will remain "None"
Example:
I'm new to programming and I'm trying to figure out this simple question! The language is Visual Basic! The Question is below:
"Users of a computer program often like to enter numbers with commas inserted in the middle, such as "1,234,000,688". Most computer languages consider this format to be non numeric. Write a program that inputs a number containing no more than three commas, and produces a string containing the same number without the commas"
When I enter this number: 1,234,000,688 and hit Display in Visual Basic I get this error message --> Argument is out of range Exception was unhanded
I'm not exactly sure why this is happening because I'm within my strUserInput length.
My Code:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'Variable declarations
Dim strUserInput = txtUserInput.Text
Dim strOutputNumber1 As String
Dim strOutputNumber2 As String
Dim strOutputNumber3 As String
Dim strOutputNumber4 As String
' 1,234,000,688
strOutputNumber1 = strUserInput.Substring(0, 1)
strOutputNumber2 = strUserInput.Substring(2, 4)
strOutputNumber3 = strUserInput.Substring(5, 8)
strOutputNumber4 = strUserInput.Substring(9, 12)
lblDisplayNumber.Text = strOutputNumber1 & strOutputNumber2 & strOutputNumber3 & strOutputNumber4
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class
You're getting that exception because of the way you're using substring, the last one there starts at index 9 and extends 12 characters...that would be a 22 character number, and the text you have as input is probably much shorter. You don't need to make things overly complicated for yourself using substrings, all of the above code could be greatly condensed and cleaned up by simply using String.Replace like this:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
lblDisplayNumber.Text = txtUserInput.Text.Replace(",", "")
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class
I have a function that gets User ID from USB badge reader, used to log in an application.
when I run the app, the log in window does not appear until I swipe the tag.
I need to know if it`s possible to load the windows, then to start running the function that gets the data from the USB.
Thanks :)
Private Sub SerialPort1_DataReceived()
'Threading.Thread.SpinWait(1000)
OpenPort()
If SerialPort1.IsOpen() Then
byteEnd = SerialPort1.NewLine.ToCharArray
'read entire string until .Newline
readBuffer = SerialPort1.ReadLine()
readBuffer = readBuffer.Remove(0, 1)
readBuffer = readBuffer.Remove(8, 1)
WWIDTextBox.AppendText(readBuffer)
End If
End Sub
Private Sub Form1_Activated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Activated
SerialPort1_DataReceived()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'SerialPort1_DataReceived()
End Sub
The problem is that you are calling the ReadLine method, which is a blocking (synchronous) method. In other words, when you call it, the method does not return the value until it has the value to return. Because of that, it stops execution on the current thread until a complete line is read (when the badge is swiped). Since you are on the UI thread when you call it, it will lock up the UI until the badge is swiped.
Instead of calling your SerialPort1_DataReceived method from the UI thread, you can do the work from a different thread. The easiest way to do that is to drag a BackgroundWorker component onto your form in the designer. Then you can add code like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
OpenPort()
If SerialPort1.IsOpen() Then
byteEnd = SerialPort1.NewLine.ToCharArray
Dim readBuffer As String = SerialPort1.ReadLine()
readBuffer = readBuffer.Remove(0, 1)
readBuffer = readBuffer.Remove(8, 1)
e.Result = readBuffer
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
WWIDTextBox.AppendText(CStr(e.Result))
End Sub
Working on VS2013, I came across the same issue, I needed to to a datagridview refresh (colors in the gridrows). This worked for me.
Sub MyForm_VisibleChanged(sender As Object, e As EventArgs) Handles Me.VisibleChanged
If Me.Visible Then
'do action...
End If
End Sub
Try Form Activated Event
Private Sub Form1_Activated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Activated
'Call your function here
End Sub
It call the function After the Form Loads...
Private Sub loadCombo()
Dim sqlconn As New OleDb.OleDbConnection
Dim connString As String
connString = ""
Dim access As String
access = "select slno from atable"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, connString)
DataAdap.Fill(DataTab)
ComboBox1.DataSource = DataTab
ComboBox1.DisplayMember = "slno"
End Sub