I am kinda new at coding.
I am reading some numbers from a txt files and i have them into a array,i managed to make them descending,now i want to make a sum with this numbers,for example:
I will have an input number 1000,on the list i will have numbers from 100 to 1000 and i want to make a sum with them to reach 1000 with minimum rest.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fStream As New System.IO.FileStream("C:\Users\Alex\Desktop\test.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Dim List As New List(Of Double)
Do While sReader.Peek >= 0
List.Add(sReader.ReadLine)
Loop
Dim i As Long
Dim txt As String
Dim thisArray As Double() = List.ToArray
For i = LBound(thisArray) To UBound(thisArray)
txt = thisArray(i) & vbCrLf
Next i
Array.Sort(thisArray)
For j As Integer = 0 To thisArray.Count - 1
Dim FILE_NAME As String = "C:\Users\Alex\desktop\test2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, IO.FileMode.Append)
objWriter.WriteLine(thisArray(j))
objWriter.Close()
Else
MessageBox.Show("File Does Not Exist")
End If
Next
fStream.Close()
sReader.Close()
End Sub
I dont know where to start to do this..input number will be from a textbox.
Related
I'm trying to retrieve data from the web to desktop using vbnet, but whenever i tried to show it on datagridview it show this error.
It only succes when i only show the first column.
But when it comes to add more column it will show at first but have error like this.
And when i tried to run it again it have error like this.
The code i use :
Imports System.Net
Imports System.IO
Public Class Form1
Dim strArr() As String
Dim strArr1() As String
Dim count, c1 As Integer
Dim str, str2 As String
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim k As Integer = 0
Dim uri As New Uri("http://localhost/tampil.php")
If (uri.Scheme = Uri.UriSchemeHttp) Then
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim pagehtml As String = reader.ReadToEnd()
response.Close()
str = pagehtml
strArr = str.Split(";")
For count = 0 To strArr.GetUpperBound(0)
ReDim Preserve strArr1(k)
strArr1(k) = strArr(count)
str2 = strArr1(k)
Dim words As String() = strArr1(k).Split(New Char() {"-"c})
If str2 = "" Then
Exit For
End If
DataGridView1.Rows.Add("")
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(0).Value = words(0)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(1).Value = words(1)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(2).Value = words(2)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(3).Value = words(3)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(4).Value = words(4)
k += 1
Next
End If
End Sub
End Class
Data from web
Can anyone help ?
Adding a row will return the index of the new row.
You can use that when updating the cell values.
This method will add the rows as you'd expect.
If there is any chance of values being returned from the html query that have a different number of elements, you should check that.
Private Sub LoadDataGridViewFromHTML(htmlValue As String)
Dim entities() As String = htmlValue.Split(Convert.ToChar(";"))
For Each entityItem As String In entities
If Not String.IsNullOrEmpty(entityItem) Then 'check you're not dealing with an empty string
Dim entityValues() As String = entityItem.Split(Convert.ToChar("-"))
Dim newRowId As Integer = DataGridView1.Rows.Add("")
DataGridView1.Rows(newRowId).Cells(0).Value = entityValues(0)
DataGridView1.Rows(newRowId).Cells(1).Value = entityValues(1)
DataGridView1.Rows(newRowId).Cells(2).Value = entityValues(2)
DataGridView1.Rows(newRowId).Cells(3).Value = entityValues(3)
DataGridView1.Rows(newRowId).Cells(4).Value = entityValues(4)
End If
Next
End Sub
I build an app, which searches for different files through the computer, including Windows, ProgramFiles, etc folders.
I've already done with the 'recursive' file search and it works now, this means all files/folders which are inaccessible will be skipped and the software will move on with the other available folders/files. But now, I have other issues...
The problem is that, for some odd reason, the application does not correctly report the progressbar value accordingly to the progress made in searching the files. This means that, the file search continues, BUT the progressbar is already 100%. The progressbar value SHOULD be 100% when the file search has been successfully completed.
====other code is already here ====
Dim int As Integer = 0
Dim filecount As Integer = 0
Private Function GetFilesRecursive(ByVal path As String) As List(Of String)
Dim lstResult As New List(Of String)
Dim stkStack As New Stack(Of String)
stkStack.Push(path)
Do While (stkStack.Count > 0)
Dim strDirectory As String = stkStack.Pop
Try
lstResult.AddRange(Directory.GetFiles(strDirectory, "*.*"))
Dim strDirectoryName As String
For Each strDirectoryName In Directory.GetDirectories(strDirectory)
stkStack.Push(strDirectoryName)
Next
Catch ex As Exception
End Try
Loop
Return lstResult
End Function
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles Quickscan.DoWork
Try
Dim i As Integer
Dim files As List(Of String) = GetFilesRecursive(FolderBrowserDialog1.SelectedPath)
For Each file As String In files
Try
Dim scanbox As New TextBox
Dim read As String = My.Computer.FileSystem.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory & "db1.db")
scanbox.Text = read.ToString
Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
Dim f As FileStream = New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
f = New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As StringBuilder = New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
If scanbox.Text.Contains(buff.ToString) Then
AddListItem(Listbox2, "" & file)
AddListItem2(Listbox2, "" & file & "")
End If
Catch ex As Exception
End Try
If (Backgroundworker1.CancellationPending = True) Then
e.Cancel = True
Exit For
End If
SetLabelText_ThreadSafe(Me.Labelscannedfiles, file & "")
i = i + 1
SetLabelText_ThreadSafe(Me.Label2, i)
Dim pct As Integer = CInt(CDbl(i) / CDbl(files.Count) * 100)
Backgroundworker1.ReportProgress(pct)
Next file
Catch ex As UnauthorizedAccessException
End Try
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles Backgroundworker1.ProgressChanged
Label28.Text = "Computer scan is in progress... Please wait"
ProgressBar1.Value = e.ProgressPercentage / 100
Any solution or help would be highly appreciated!
In your DoWork() method...
Change:
For Each file As String In GetFilesRecursive(FolderBrowserDialog1.SelectedPath)
To:
Dim i As Integer ' <- you didn't actually declare a counter before
Dim files As List(Of String) = GetFilesRecursive(FolderBrowserDialog1.SelectedPath)
For Each file As String In files
Now you can get the count from "files" and use that in your percentage calculation:
i = i + 1 ' <-- increment our "i" counter
SetLabelText_ThreadSafe(Me.Label2, i)
Dim pct As Integer = CInt(CDbl(i) / CDbl(files.Count) * 100)
backgroundworker1.ReportProgress(pct)
my code is not working please, help
Private Sub Form3_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim sReader As New System.IO.StreamReader(Form1.pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt")
Dim strValues(11) As String
Dim counter As Integer = 0
While sReader.Peek <> 1
strValues(counter) = sReader.ReadLine
counter += 1
End While
counter = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
sReader.Close()
I have changed to the File class to accomplish your task. You do not need to declare an instance of File. A StreamReader needs to be not closed but disposed. A Using...End Using block or Try...Finally...End Try to ensure the closing and disposing of a StreamReader so the File class is easier to use.
You do not need to declare a size for the strValues because it is initialize at declaration. I added a check that the two arrays are the same size.
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
Dim path As String = pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt"
Dim strValues = File.ReadAllLines(path) 'Returns a string array
If lblControls.Length <> strValues.Length Then
MessageBox.Show("Labels do not equal data.")
Return
End If
Dim counter As Integer = 0
For Each lbl As Label In lblControls
lbl.Text = strValues(counter)
counter += 1
Next
End Sub
I'm making a programme that creates a bingo card for 100 people and gives them all different numbers. but just now the code that i have is giving everyone the exact same 15 numbers. any help would be greatly appreciated, thanks.
Structure Number
Dim number As Integer
End Structure
Structure Player
Dim name As String
Dim numbers() As Number
Dim numbers_left As Integer
End Structure
Dim players As New List(Of Player)
Dim selectednumber As Integer
Dim used As New List(Of Integer)
Dim random As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number As Number
Dim player As Player
ReDim player.numbers(14)
For i = 1 To 100
For j = 0 To 14
SelectNumber: Number.number = random.Next(1, 101)
If player.numbers IsNot Nothing Then
For Each item In player.numbers
If item.number = Number.number Then
GoTo SelectNumber
End If
Next
End If
player.numbers(j).number = Number.number
Next
player.name = ("Bill" & i)
player.numbers_left = 15
players.Add(player)
Next
End Sub
I'll admit I'm not completely following all the logic, but it looks like you need to re-initialize the player at each loop, since I think you're always testing against the first player.
Structure Number
Dim number As Integer
End Structure
Structure Player
Dim name As String
Dim numbers() As Number
Dim numbers_left As Integer
End Structure
Dim players As New List(Of Player)
Dim selectednumber As Integer
Dim used As New List(Of Integer)
Dim random As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 1 To 100
Dim Number As Number
Dim player As Player
ReDim player.numbers(14)
For j = 0 To 14
SelectNumber: Number.number = random.Next(1, 101)
If Player.numbers IsNot Nothing Then
For Each item In Player.numbers
If item.number = Number.number Then
GoTo SelectNumber
End If
Next
End If
Player.numbers(j).number = Number.number
Next
Player.name = ("Bill" & i)
Player.numbers_left = 15
players.Add(Player)
Next
End Sub
My problem here is that i have 3 radiobuttons for 3 different categories:
Huse Folii and Altele.
The idea is when i select a radiobutton,the filepath will change to Huse,Folii or Altele.
For example i tried to make _path :
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
then use the _path here:
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
but it didn't worked,for sure i do something wrong,but i can't find how or where to use that _path...
Here is the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
End If
If RadioButton2.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Folii\")
End If
If RadioButton3.Checked = True Then
IO.Path.
Dim _path As String = IO.Path.Combine("C:\Descriere\Altele\")
End If
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
TextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Dim ioFile2 As New System.IO.StreamReader(path:=+"core.txt")
Dim lines2 As New List(Of String)
Dim rnd2 As New Random()
Dim line2 As Integer
While ioFile2.Peek <> -1
lines2.Add(ioFile2.ReadLine())
End While
line2 = rnd2.Next(lines2.Count + 1)
TextBox1.AppendText(lines2(line2).Trim())
ioFile2.Close()
ioFile2.Dispose()
Dim ioFile3 As New System.IO.StreamReader(path:=+"x.txt")
Dim lines3 As New List(Of String)
Dim rnd3 As New Random()
Dim line3 As Integer
While ioFile3.Peek <> -1
lines3.Add(ioFile3.ReadLine())
End While
line3 = rnd3.Next(lines3.Count + 1)
TextBox1.AppendText(lines3(line3).Trim())
ioFile3.Close()
ioFile3.Dispose()
TextBox1.Text = Replace(TextBox1.Text, "BRAND", TextBox2.Text)
TextBox1.Text = Replace(TextBox1.Text, "MODEL", TextBox3.Text)
Dim count As Integer = 0
count = TextBox1.Text.Split(" ").Length - 1
Label5.Text = "Caractere:" & Len(TextBox1.Text)
End Sub
You are using IO.Path.Combine but you have nothing to Combine at the place of use in your code. You have to use IO.Path.Combine later in your code because this is a method to Combine part of a path and a filename e.g. set your _path first and combine in a second step. Please note this code is not tested for your needs, because your coding is not clear to me.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim directoryName As String = "D:\"
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
directoryName = "D:\Descriere\Huse"
End If
If RadioButton2.Checked = True Then
directoryName = "D:\Descriere\Folii"
End If
If RadioButton3.Checked = True Then
'//--- IO.Path.
directoryName = "D:\Descriere\Altele"
End If
Dim ioFile As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "a.txt"))
...
Dim ioFile2 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "core.txt"))
...
Dim ioFile3 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "x.txt"))
...
End Sub
Please use the debugger of your IDE because your code isn't clean e.g. a hanging aroung IO.Path.