How to add new display in textbox without replacing the first input - vb.net

Hi I am creating a chat like application. Can you kindly help me?
When I am entering a new message the initial displayed message is getting replaced :(
Please see my codes below:
Private Sub saveMessage()
FileName = Format(Now, "MMddyyyyhhmmss")
Dim RecipientFile As String
If CurrentRecipient = "Edward" Then
RecipientFile = RecipientFolder & FileName & ".txt"
ElseIf CurrentRecipient = "Criziel" Then
RecipientFile = RecipientFolder & FileName & ".txt"
ElseIf CurrentRecipient = "Jerome" Then
RecipientFile = RecipientFile & FileName & ".txt"
Else
Exit Sub
End If
Dim Writer As IO.StreamWriter
Writer = New IO.StreamWriter(RecipientFile)
Writer.Write(MainRichTextBox.Text)
Writer.Close()
ShowtextRichTextBox.Text = (User & " : ") & MainRichTextBox.Text
MainRichTextBox.Clear()
End Sub
Thank you in advance ! :*

Your below code is just assigning (replacing) the latest value to the Rich TextBox,
ShowtextRichTextBox.Text = (User & " : ") & MainRichTextBox.Text
Instead, you should append the text as below,
ShowtextRichTextBox.Text &= (User & " : ") & MainRichTextBox.Text
Also, you can try the inbuild method of RichTextBox to append the text like, ShowtextRichTextBox.AppendText((User & " : ") & MainRichTextBox.Text)
Note: When appending, you should also add newline before the new text like, ShowtextRichTextBox.Text &= Environment.NewLine & (User & " : ") & MainRichTextBox.Text.
Modified code,
Private Sub saveMessage()
FileName = Format(Now, "MMddyyyyhhmmss")
Dim RecipientFile As String
If CurrentRecipient = "Edward" Then
RecipientFile = RecipientFolder & FileName & ".txt"
ElseIf CurrentRecipient = "Criziel" Then
RecipientFile = RecipientFolder & FileName & ".txt"
ElseIf CurrentRecipient = "Jerome" Then
RecipientFile = RecipientFile & FileName & ".txt"
Else
Exit Sub
End If
Dim Writer As IO.StreamWriter
Writer = New IO.StreamWriter(RecipientFile)
Writer.Write(MainRichTextBox.Text)
Writer.Close()
ShowtextRichTextBox.Text &= Environment.NewLine & (User & " : ") & MainRichTextBox.Text
MainRichTextBox.Clear()
End Sub

Related

VB.NET ComboBox selected item not remains effect than 2 times

I have a VB windows form application that has 02 ComboBox that provide newname input for a renaming file event. The first combobox provide prefix for new name comprise items (aa, bb, cc,... can add more through keydown button click event), the other combobox provide main name comprise items (XX, YY, ZZ,.. can also add more through keydown button click event). When I select "aa" from the first combobox, "XX" from the other then fire the rename event, the new file name should be "aa - XX", if file "aa - XX" has already existed then add "1" to the last as "aa - XX 1" and so on and if no item selected in prefix combobox the newname just be "XX" and increment. I get the old file name through a system openfiledialog. My code for rename as follows:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim var As String, prfix As String
var = ComboBox1.Text
prfix = ComboBox2.Text
If ComboBox2.Text = Nothing Then
If File.Exists(n & "\" & var & extn) = False Then
My.Computer.FileSystem.RenameFile(OpenFD.FileName, var & extn)
Else
Dim i As Integer = 1
Dim newfn As String = var & " " & i & extn
Dim m As String = n & "\" & newfn
While File.Exists(m)
newfn = var & " " & i & extn
m = n & "\" & newfn
i += 1
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn)
End If
Else
If File.Exists(n & "\" & prfix & " - " & var & extn) = False Then
My.Computer.FileSystem.RenameFile(OpenFD.FileName, prfix & " - " & var & extn)
Else
Dim j As Integer = 1
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
Dim k As String = n & "\" & newfn1
While File.Exists(k)
newfn1 = var & " " & j & extn
k = n & "\" & newfn1
j += 1
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn1)
End If
End If
MessageBox.Show("Select a next file")
End Sub
My code run well 2 times. After I select "aa" and "XX" and leave it to rename, first result is "aa - XX", the second result is "aa - XX 1" but the third result is "XX", the forth is "XX 1" and then incrementing so on while the result should be "aa - XX 2" and next increment. I don't understand why combobox1 still effective but combobox2 as Nothing after no re-selecting the item in both comboboxes (2 times). I'm very new with VB so any advice should be much appreciated. Thanks.
In your lower Else block, you were incorrectly building up the file name.
You build up the first "newfn1" with:
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
But then below, you used:
newfn1 = var & " " & j & extn
Notice the missing prefix and dash parts at the beginning.
Here's the full corrected version:
Dim j As Integer = 1
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
Dim k As String = Path.Combine(n, newfn1)
While File.Exists(k)
j = j + 1
newfn1 = prfix & " - " & var & " " & j & extn
k = Path.Combine(n, newfn1)
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn1)
I'm a little confused by your explanation but if I understand correctly this should help,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CreateFile()
End Sub
Private BasePath As String = "" 'TODO
Private Ext As String = "txt"
Private Sub CreateFile()
If ComboBox1.SelectedIndex < 0 OrElse
ComboBox2.SelectedIndex < 0 OrElse
ComboBox1.SelectedItem.ToString = "" OrElse
ComboBox2.SelectedItem.ToString = "" Then
'error message
Exit Sub
End If
Dim fileName As String = String.Format("{0}-{1}.{2}",
ComboBox1.SelectedItem.ToString,
ComboBox2.SelectedItem.ToString,
Ext)
fileName = IO.Path.Combine(BasePath, fileName)
Dim ct As Integer = 1
Do While IO.File.Exists(fileName)
fileName = String.Format("{0}-{1}{3}.{2}",
ComboBox1.SelectedItem.ToString,
ComboBox2.SelectedItem.ToString,
Ext,
ct)
fileName = IO.Path.Combine(BasePath, fileName)
ct += 1
Loop
Dim fs As IO.FileStream = IO.File.Create(fileName)
fs.Close()
fs.Dispose()
End Sub

Writing large amounts of data to a csv file

I couldn't find anything specific to this so here goes.
I have a For Each loop where I want to write values to a csv file. Currently, I use a WriteToFile function:
Public Sub WriteToFile(stuff as string, morestuff as string, moremorestuff as string))
Dim strFile As String = "\\SomeServer\somefilepath\WriteTo.csv"
Try
If System.IO.File.Exists(strFile) = True Then
'rename with startdate and enddate. Always want to create new
Dim objWriter As New System.IO.StreamWriter(strFile, True)
objWriter.WriteLine(Stuff & "," & MoreStuff & "," & Moremorestuff)
objWriter.Close()
Else
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(strFile)
writeFile.WriteLine("Stuff" & "," & "MoreStuff" & "," & "MoreMoreStuff")
writeFile.WriteLine(Stuff & "," & MoreStuff & "," & MoreMoreStuff)
writeFile.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured in the WriteToFile subroutine: " & ex.ToString) ' & vbCrLf & strPlugin & vbCrLf & strVersion)
End Try
End Sub
Rather than closing the StreamWriter after every record is written, is there a way to keep it open? Or should it be kept open?
I made some changes and came up with this. However, using this code, how would I create a header in the csv file?
If cur.Count > 0 Then
Using writer As System.IO.StreamWriter = New IO.StreamWriter("C:\Temp\UWConditions.csv")
For Each lrdata As LoanReportData In cur
loan = session.Loans.Open(lrdata.Guid)
If Not IsNothing(loan) Then
For Each condition As UnderwritingCondition In loan.Log.UnderwritingConditions
Title = condition.Title.Replace(",", "")
Desc = condition.Description.Replace(",", "")
UWName = loan.Session.Users.GetUser(loan.Fields("UWID").Value).FullName.Replace(",", "")
writer.WriteLine(lrdata("Loan.LoanNumber") & "," & Title & "," & Desc & "," & UWName)
Next
loan.Close()
End If
Next
End Using
End If

VBA/Access: How to stop "You... FORM to be active window"

I want to be able to tell IF a form is the active window.
It seems simply invoking that method produces an error. I guess I could catch that error and run with it, but it's a backwards way of doing it.
Screen.ActiveForm.Name
This needs a form to be active. If I am breaking any rules of stackOverflow please be kind and remind me as I am new to forum.
Screen.parent, screen.activeControl, etc. What if VBA editor is open, as often it is?
Function CStatus(strStatus, ByRef intType As Integer, Optional ByRef erNo, Optional erMsg, Optional strDatum)
'pXname = "CStatus"
'pXStack = Left(pXStack, 500) & ">" & pXname
'Updates and manages the status bar
Dim strPreamble As String, strOut As String, strForm As String, strComment As String, strSQL As String, strPxStack As String, strCErrStack As String
Dim intColor As Double
Dim intPreLen As Integer
'On Error GoTo err_hand
'Color Codes
'12632256 = Lt Grey
'33023 = Orange
'65280 = Green
'16744576 = Steel Grey
'Define "Constants"
intPreLen = 350 'Length of previous message cache
'** Fix missings
If (IsMissing(strDatum) = True) Then strDatum = "[N/A]"
'** Other inits
strWindow = Screen.Parent.Name
strForm = Screen.ActiveForm.Name
'** intDebug ' Minimum Level of to report to status
'bEcho = True 'Whether to echo to status
intColor = errNoColor(intType)
'Error-level idiot explanations
strComment = "0"
If IsMissing(erNo) Then erNo = 0
If (IsNull(erMsg) = False) Then
If IsMissing(erMsg) = False Then strComment = erMsg
End If
strComment = errorTree(erNo)
strPreamble = Left(strPreamble, intPreLen) & "..."
strErrStack = Left(strErrStack, intPreLen) & " > " & pXname & ":" & intType
strCErrStack = strErrStack
reS:
If ((strForm = "finvmain") Or (strForm = "fclips")) Then Screen.ActiveForm.timeStatusUpdated = Now() 'Small field keeps time
If bEcho = True Then
strPxStack = ""
strCErrStack = "" 'Internal error stack
End If
strOut = Now() & " " & intType & " (" & strType & "): " & erNo & " " & strCErrStack & " >> " & strComment & " / " & strStatus & " [" & strDatum & "] .. " & strPreamble
If bEcho = True Then
If (strForm = "fInvMain") Then Screen.ActiveForm.txtStatus2 = Screen.ActiveForm.txtStatus 'Added second window to show previous message
Screen.ActiveForm.txtStatus = strOut
End If
Screen.ActiveForm.txtStatus.ForeColor = intColor
If strForm = "fInvMain" Then strTag = Screen.ActiveForm.Controls("txttag").value
'***Event Log
If erNo = "" Then erNo = 0
If IsMissing(erMsg) = True Then erMsg = ""
If IsMissing(strDatum) = True Then strDatum = ""
If Len(strPreamble) < 2 Then strPreamble = "[None]"
'Fixxed - Syntax Error for Some Odd Reason! Apr 27th
If ((strTag = Empty) And (strForm = "fInvMain")) Then strTag = Screen.ActiveForm.txtTag 'Attempt to add tag# to entry
strStatus = cleanString(strStatus)
strDatum = cleanString(strDatum)
strComment = cleanString(strComment)
strSQL = "INSERT INTO tEvents(txtdate, myerrno, interrno, myerrmsg, interrmsg, txtform, stack, process, Datum, idLink) VALUES ('" & Now() & "','" & intType & "','" & erNo & "','" & strStatus & "','" & strComment & "','" & strForm & "','" & strErrStack & "','" & pXname & "','" & strDatum & "','" & strTag & "');"
CurrentDb.Execute strSQL, dbFailOnError
Exit Function
err_hand:
If Err.Number = 2475 Then
bEcho = False
Resume reS
Else: MsgBox "555: CStatus Internal Error, Turn off error handling to view"
End If
End Function
I need a boolean true or false IF form is active. If it isn't, I can't put stuff into a textbox in that.
To determine if a particular form is open then set focus to form:
If CurrentProject.AllForms("finvmain").IsLoaded
strForm = "finvmain"
Elseif CurrentProject.AllForms("fclips").IsLoaded Then
strForm = "fclips"
End If
If strForm <> "" Then DoCmd.SelectObject acForm, strForm

VB.NET StreamReader can't follow Process

I tried to get output in console program, but i got error
maybe I think that the error is about 'deadlock'
I pass night without sleep doing search solution that this error, I can't find
anyone can help me?
Someone tell me about the solution to fix it, it seems to make inherit system.
and he refer : http://programming.nullanswer.com/question/27270022
but this is java not vb.net.
Error Message:
'CTextConsoleWin32::GetLien: !GetNumberOfConsoleInputEvents'
Dim cmdCommand As String
getgame()
Serverlog.Clear()
Serverlog.Text += "ServerName : " & SelectedServer.Item(8) & " / " & "Server Download Path : " & SelectedServer.Item(9) & vbCrLf
Dim mapname As String = Split(SelectedServer.Item(2), ".bsp")(0)
cmdCommand = "-console -game " & SelectedServerGame & " -tickrate " & SelectedServer.Item(5) & " -port " & SelectedServer.Item(11) & " -maxplayers_override " & SelectedServer.Item(4) & " +map " & mapname
Serverlog.Text += (cmdCommand) & vbCrLf
Dim start_info As New ProcessStartInfo()
start_info.FileName = SelectedServer.Item(0)
start_info.UseShellExecute = False
'start_info.CreateNoWindow = True
start_info.RedirectStandardError = True
start_info.RedirectStandardOutput = True
start_info.RedirectStandardInput = True
'start_info.WindowStyle = ProcessWindowStyle.Hidden
start_info.Arguments = cmdCommand
Dim proc As New Global.System.Diagnostics.Process
proc.StartInfo = start_info
proc.Start()
Dim std_out As StreamReader = proc.StandardOutput
Do
proc.WaitForInputIdle()
Dim line As String = Await std_out.ReadLineAsync()
'Serverlog.Text += std_out.ReadLine & vbCrLf
Serverlog.Invoke(Sub() Serverlog.Text += line & vbCrLf)
Loop While proc.HasExited = False

Could not complete operation on some files

The below code basically takes a directory, copies it the zips it up. This has worked perfectly for me for the last 6 months
Dim tempMail As String = Temp
Dim startpath As String = tempMail & tvProgress.SelectedNode.FullPath
Dim outMail As String = "c:\LTEMP\"
Dim fileout As String = outMail & tvProgress.SelectedNode.Text
Dim tempfolder As String = "c:\LTEMP" & "\" & tvProgress.SelectedNode.FullPath
Dim Reality As String = "\Reality Stock Report"
Dim enUK As New CultureInfo("en-GB")
Try
Dim x As Integer
Dim q As Integer
Dim inMail As String = FileStr
If CheckInternet() = False Then
MessageBox.Show("No internet connection is detected!" & vbNewLine & vbNewLine & "This job will still be added to completed but you will need to connect to the internet to complete sending this file to CIS", "Internet Connection Check", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End If
If tvProgress.SelectedNode.Parent.Text = "Archive" Then Call INIDate()
Dim Datey As String = Nothing
If tvProgress.SelectedNode.Parent.Text <> "Archive" Then
Datey = Date.ParseExact(Convert.ToDateTime(tvProgress.SelectedNode.Parent.Text), "dd/MM/yy", enUK)
Else
For q = 0 To UBound(INIdet)
If tvProgress.SelectedNode.Parent.Text = "Archive" Then Datey = INIdet(q).iDate
Next
End If
If My.Computer.FileSystem.FileExists(startpath & Reality & ".docx") Then
Call Word2Pdf(startpath & Reality & ".docx", startpath & Reality & ".pdf")
End If
System.Threading.Thread.Sleep(150)
For x = 0 To UBound(AllDetails)
If AllDetails(x).uName & " - " & AllDetails(x).uCode & " - " & AllDetails(x).uOps = tvProgress.SelectedNode.Text Then
If AllDetails(x).uPlan <> Datey Then
DateCh.Show()
Exit Sub
End If
End If
If AllDetails(x).uName & " - " & AllDetails(x).uCode & " - " & AllDetails(x).uOps & " - " & AllDetails(x).uPlan = tvProgress.SelectedNode.Text & " - " & Datey Then
Application.DoEvents()
My.Computer.FileSystem.CopyDirectory(startpath, tempfolder, True)
Directory.CreateDirectory(fileout & "\")
With tempfolder
For Each xDir As String In Directory.GetFiles(tempfolder)
If Not ((UCase(Path.GetDirectoryName(xDir)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("BARS")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("TCMS"))) Then
File.Copy(xDir, Path.Combine(fileout, Path.GetFileName(xDir)), True)
End If
Next
If Directory.Exists(tempfolder & "\Controller") Then
For Each xDir As String In Directory.GetFiles(tempfolder & "\Controller")
If Not ((UCase(Path.GetDirectoryName(xDir)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("BARS")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("TCMS"))) Then
File.Copy(xDir, Path.Combine(fileout, Path.GetFileName(xDir)), True)
End If
Next
End If
If Directory.Exists(tempfolder & "\Capcon") Then
For Each xDir As String In Directory.GetFiles(tempfolder & "\Capcon")
If Not ((UCase(Path.GetDirectoryName(xDir)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("BARS")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("TCMS"))) Then
File.Copy(xDir, Path.Combine(fileout, Path.GetFileName(xDir)), True)
End If
Next
End If
If Directory.Exists(tempfolder & "\Capcas") Then
For Each xDir As String In Directory.GetFiles(tempfolder & "\Capcas")
If Not ((UCase(Path.GetDirectoryName(xDir)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("BARS")) Or (UCase(Path.GetDirectoryName(xDir)).Contains("TCMS"))) Then
File.Copy(xDir, Path.Combine(fileout, Path.GetFileName(xDir)), True)
End If
Next
End If
End With
Dim zip As String = inMail & AllDetails(x).uFile & ".zip"
Dim txt As String = inMail & AllDetails(x).uFile & ".txt"
Dim pdf As String = inMail & AllDetails(x).uFile & ".pdf"
Dim fldr As String = FileStr & AllDetails(x).uFile
ZipFile.CreateFromDirectory(fileout & "\", fileout & ".zip", CompressionLevel.Optimal, False)
My.Computer.FileSystem.CopyFile(fileout & ".zip", ArcFolder & tvProgress.SelectedNode.Text & Date.Parse(AllDetails(x).pDate).ToString(" - dd-MM-yyyy") & ".zip", True)
My.Computer.FileSystem.MoveFile(fileout & ".zip", FileStrOut & tvProgress.SelectedNode.Text & ".zip", True)
My.Computer.FileSystem.DeleteDirectory(fileout, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.DoNothing)
If My.Computer.FileSystem.FileExists(zip) Then
My.Computer.FileSystem.MoveFile(zip, "c:\LTEMP\" & AllDetails(x).uFile & ".zip", True)
End If
If My.Computer.FileSystem.FileExists(txt) Then
My.Computer.FileSystem.CopyFile(txt, ArcFolder & AllDetails(x).uFile & ".txt", True)
My.Computer.FileSystem.MoveFile(txt, "c:\LTEMP\" & AllDetails(x).uFile & ".txt", True)
End If
If My.Computer.FileSystem.FileExists(pdf) Then
My.Computer.FileSystem.MoveFile(pdf, "c:\LTEMP\" & AllDetails(x).uFile & ".pdf", True)
End If
With fldr
If My.Computer.FileSystem.DirectoryExists(fldr) Then
Directory.Delete(fldr, True)
End If
End With
System.Threading.Thread.Sleep(150)
End If
Next
My.Computer.FileSystem.DeleteDirectory(tempMail & tvProgress.SelectedNode.FullPath, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin)
tvProgress.BeginUpdate()
tvProgress.SelectedNode.Remove()
tvProgress.EndUpdate()
Dim sRoot As String = tempMail
Dim sPath As String = tempMail
DeleteEmptyFolders(sPath, sRoot)
lstPlanned.BeginUpdate()
Call TxtRfrsh()
Call RfshArray()
Call CompleteArray()
Call ltempfiles()
lstPlanned.EndUpdate()
Catch ex As Exception
MsgBox(ex.Message)
End Try
I've recently added the following bit of code which calls a routine that converst a docx file to a pdf (works fine on its own)
If My.Computer.FileSystem.FileExists(startpath & Reality & ".docx") Then
Call Word2Pdf(startpath & Reality & ".docx", startpath & Reality & ".pdf")
End If
System.Threading.Thread.Sleep(150)
The called sub
Public Sub Word2Pdf(ByVal infile As String, ByVal outfile As String)
Dim wordApp As Word.Application = Nothing
Try
wordApp = New Word.Application()
wordApp.Documents.Open(infile)
wordApp.ActiveDocument.ExportAsFixedFormat(outfile, Word.WdExportFormat.wdExportFormatPDF)
Finally
If wordApp IsNot Nothing Then
wordApp.Quit()
End If
End Try
End Sub
Now when the criteria is met to call the above sub I'm getting the Could not complete operation on some files error. When I check the directory the PDF has been created but its not then completing the rest of the zip and copy routine.
Any ideas??
WordApp probably has one of the files locked. Check to make sure WordApp has finished execution before you continue. The Sleep(150) is apparently not long enough.