I have the following code in VB6
Private Sub Command1_Click()
Dim encryptedFileName As String
Dim decrypToFileName As String
encryptedFileName = "Some File Name"
decrypToFileName = "Some Other File Name"
Dim afileDecryptor As fileDecryptor
afileDecryptor = New fileDecryptor
afileDecryptor.Decrypt(encryptedFileName, decrypToFileName)
End Sub
class FileDecryptor has the following Sub:
Public Sub Decrypt(ByVal fileNameToDecrypt As String, ByVal decrypToFileName As String)
End Sub
I keepp geting compiler errot, Expected:= on the line
afileDecryptor.Decrypt(encryptedFileName, decrypToFileName)
I have looked at the everything I can , and still don't understand what the problem is
Subs don't return anything so you shouldn't have the parentheses around it's parameters.
afileDecryptor.Decrypt encryptedFileName, decrypToFileName
Related
I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.
I have created a simple VB 6.0 program to calculate day-to-day sales. I have converted this project into an .exe file where other users can run this program in their terminal to work with, but when they run this exe file they get above mentioned runtime error. Can anyone tell me how to overcome this error?
Dim myobject As Object
Private Sub Command1_Click()
Set myobject = Nothing
Adodc1.Recordset.AddNew
End Sub
Private Sub Command2_Click()
Adodc1.Recordset.Update
MsgBox "Your Record Updated Successfully!!", vbInformation
End Sub
Private Sub Command3_Click()
Text19.Text = Val(Text11) + Val(Text12) + Val(Text13) + Val(Text14) + Val(Text15)
End Sub
I am creating a start-up 2nd level logon screen for businesses and corporate companies to use. However, I am trying to disable using Task Manager by using a Registry DWORD Value. When I add in the code, it comes up with the error "Comma, ')', or a valid expression continuation expected". What can I do?
Imports Microsoft.Win32
Public Class Form1
Dim regKey As RegistryKey
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
regKey = Registry.CurrentUser.OpenSubKey("regKey.SetValue("***HKEY***\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System")
regKey.SetValue("DisableTskMgr", 1, RegistryValueKind.DWord)
End Sub
Private Sub frmMyform_FormClosing(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim Cancel As Boolean = eventArgs.Cancel
Dim UnloadMode As System.Windows.Forms.CloseReason = eventArgs.CloseReason
If UnloadMode = CloseReason.UserClosing Then
Cancel = True
End If
End Sub
End Class
My problem is with the HKEY system above. Thanks in advance!
I think this should look like this:
regKey = Registry.CurrentUser.OpenSubKey( "regKey.SetValue(""***HKEY***\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"")" )
See Escape double quote in VB string
MsgBox("""") ' Prints a single "
I have a problem trying to catch the completion of a stored proc execute asynchronously.
Below my code VBA (in a class module named clsAsync):
Option Explicit
Private WithEvents cnn As ADODB.Connection
Private Sub cnn_ExecuteComplete(ByVal RecordsAffected As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pCommand As ADODB.Command, ByVal pRecordset As ADODB.Recordset, ByVal pConnection As ADODB.Connection)
MsgBox "Execution completed"
End Sub
Sub execSPAsync()
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.ConnectionString = "connection to my database SQLSEREVER"
cnn.Open
cnn.Execute "kp.sp_WaitFor", adExecuteNoRecords, adAsyncExecute
End Sub
This class is PublicNotCreatable.
To call the sub execSPAsync from a module I use the following code:
Sub testASYNC()
Dim a As New clsAsync
Call a.execSPAsync
End Sub
The stored procedure is very simple:
alter PROC kp.sp_WaitFor
AS
WAITFOR DELAY '00:00:05'
My problem is that the event ExecuteComplete is not fired at all, while if I comment the adAsynExecute parameter all is working fine.
Any idea on how to solve my question?
I solved my problem replacing the calling code:
Sub testASYNC()
Dim a As New clsAsync
Call a.execSPAsync
End Sub
with this new code:
Private a As clsAsync
Sub testASYNC()
Set a = New clsAsync
Call a.execSPAsync
End Sub
In the async mode, the object "a" is no longer available at the end of the procedure (scope visibility issue).
I was following this MSDN guide on creating custom events. I feel like I understand the process now, but I cannot figure out why I am getting a Compile Error: Event Not Found for RaiseEvent ItemAdded. The weird thing is, the ItemAdded event is recognized by the IDE (I can type it in all lowercase and it is then automatically formatted properly), so I know that it is recognized by VB.
DataComboBox Class Module Code:
Public Event ItemAdded(sItem As String, fCancel As Boolean)
Private pComboBox As Control
Public Property Set oComboBox(cControl As Control)
Set pComboBox = cControl
End Property
Public Property Get oComboBox() As Control
oComboBox = pComboBox
End Property
Private Sub Class_Initialize()
End Sub
Private Sub Class_Terminate()
End Sub
The UserForm contains two controls - a CommandButton named btnAdd and a ComboBox named cboData.
UserForm Code:
Private WithEvents mdcbCombo As DataComboBox
Private Sub UserForm_Initialize()
Set mdcbCombo = New DataComboBox
Set mdcbCombo.oComboBox = Me.cboData
End Sub
Private Sub mdcbCombo_ItemAdded(sItem As String, fCancel As Boolean)
Dim iItem As Long
If LenB(sItem) = 0 Then
fCancel = True
Exit Sub
End If
For iItem = 1 To Me.cboData.ListCount
If Me.cboData.List(iItem) = sItem Then
fCancel = True
Exit Sub
End If
Next iItem
End Sub
Private Sub btnAdd_Click()
Dim sItem As String
sItem = Me.cboData.Text
AddDataItem sItem
End Sub
Private Sub AddDataItem(sItem As String)
Dim fCancel As Boolean
fCancel = False
RaiseEvent ItemAdded(sItem, fCancel)
If Not fCancel Then Me.cboData.AddItem (sItem)
End Sub
You cannot raise an event outside the classes file level.
Add a routine like this inside "DataComboBox1" to allow you to raise the event externally.
Public Sub OnItemAdded(sItem As String, fCancel As Boolean)
RaiseEvent ItemAdded(sItem, fCancel)
End Sub
Then call the OnItemAdded with the current object.
Example...
Private WithEvents mdcbCombo As DataComboBox
...
mdcbCombo.OnItemAdded(sItem, fCancel)