vb.net loop through list box contains path for rtf files then convert to html code then insert to datagridview - vb.net

I have a problem with vb.net code, after i finished with all codes that get files from path then loop through this list to get RTF text then convert it to HTML... until here everything is okay
my problem starts here>>> inserting the result to new row in datagridview it just does this to first row, then stops after that!
here's the codes
For i = 0 To ListBox1.Items.Count - 1
'get RTF files...
RichTextBox1.LoadFile(ListBox1.Items(i).ToString(),
RichTextBoxStreamType.RichText)
RichTextBox1.SelectAll()
RichTextBox1.SelectionAlignment =
HorizontalAlignment.Right
'Convert to html method...
converttohtml()
'just for fallow the process
MsgBox("Ok " + i.ToString())
'insert new row with the html result
DataGridView1.Rows.Insert(i, New String() {RichTextBox2.Text, RichTextBox1.Text})
'increase progress by one
ProgressBar1.Value += 1
Next

my problem fixed... by help of a freelancer ... here's the code
'add column to datagridview ...
Dim col As New DataGridViewTextBoxColumn
col.DataPropertyName = "cellvalue"
col.HeaderText = "Article"
col.Name = "Article"
DataGridView1.Columns.Add(col)
'second coulmn...
Dim cols As New DataGridViewTextBoxColumn
cols.DataPropertyName = "cellnumber"
cols.HeaderText = "number"
cols.Name = "number"
DataGridView1.Columns.Add(cols)
'third coulmn...
Dim colsa As New DataGridViewTextBoxColumn
colsa.DataPropertyName = "cellnumber"
cols.HeaderText = "number"
colsa.Name = "number"
DataGridView1.Columns.Add(colsa)
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
ProgressBar1.Value = 0
Dim x As Integer = 0
For i = 0 To ListBox1.Items.Count - 1
'get RTF files...
RichTextBox1.LoadFile(ListBox1.Items(i).ToString(),
RichTextBoxStreamType.RichText)
RichTextBox1.SelectAll()
RichTextBox1.SelectionAlignment =
HorizontalAlignment.Right
'Convert to html method...
converttohtml()
'just for fallow the process
MsgBox("Ok " + i.ToString())
'insert new row with the html result
DataGridView1.Rows.Insert(i, New String()
{RichTextBox2.Text, RichTextBox1.Text, xstring})
'increase progress by one
ProgressBar1.Value += 1
Next
End Sub
cells just needed to be wrap... BY M P.

Related

Insert custom text on datagridview row export to TXT

For the code below, I want to put at the beginning of each line exported in TXT the following text : "S,1,___,,;" + the row exported from database.
How can I add for each line that text on export? For the moment I have the text only on the firs line ( check pictures attached)
If DataGridView1.RowCount = 0 Then
MessageBox.Show("Lista este goala")
Else
If Directory.Exists("C:\test") = False Then
Directory.CreateDirectory("C:\test")
End If
Dim sFile As String = "C:\test\test.txt"
If File.Exists(sFile) = True Then
My.Computer.FileSystem.DeleteFile(sFile,
FileIO.UIOption.OnlyErrorDialogs,
FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
End If
Using f As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim a As String = "S,1,______,_,__;"
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView1.Rows
For Each c As DataGridViewColumn In DataGridView1.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView1.Rows.Count - 1 Then row &= Environment.NewLine
Next
f.WriteLine(a & row)
End Using
Using f2 As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView3.Rows
For Each c As DataGridViewColumn In DataGridView3.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView3.Rows.Count - 1 Then Row &= Environment.NewLine
Next
f2.WriteLine("T,1,______,_,__;" & row)
f2.Close()
MessageBox.Show("Bon printat")
End Using
End If
And also a picture with exported file:
the red circled line is the way that I need for export
the red circle string from code is my input which is mandatory for each line followed by DGV lines export.
Actual TXT export
Actual Code for input my mandatory text before DGV export
Thanks!
Provide some debug detail like what is Rows.Count etc.
If it is not going inside loop and even there are rows, better you try with accessing object in DataSource.
Something like ForEach loop on ((DataTable)DataGridView1.DataSource).Rows

I want to align Dynamic pictureboxs with Dynamic Labels

Here is my function that allows me to get from a webpage the image link for my PictureBoxs and the title for my labels
Public Shared Function getPics(website As String, pattern As String)
Dim tempTitles As New List(Of String)()
Dim tempTitles2 As New List(Of String)()
Dim lestitres As New List(Of titlesclass)
Dim webClient As New WebClient()
webClient.Headers.Add("user-agent", "null")
Dim counter As Integer = 0
Dim counter2 As Integer = 0
Dim counter3 As Integer = 0
Dim counter4 As Integer = 1
Dim counter5 As Integer = 0
Dim counter6 As Integer = 0
'If the website happens to go offline, at least your application wont crash.
Dim content As String = webClient.DownloadString(website)
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
Key .Title = title.Groups("Dataa").Value}
For Each letitre In query.Distinct
'MsgBox(letitre.Link & " ======= " & letitre.Title)
Next
'For Each title As Match In (New Regex(pattern).Matches(content)) 'Since you are only pulling a few strings, I thought a regex would be better.
' Dim letitre As New titlesclass
' letitre.Link = title.Groups("Data").Value
' letitre.Title = title.Groups("Dataa").Value
' lestitres.Add(letitre)
' 'tempTitles2.Add(title.Groups("Dataa").Value)
'Next
Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
'Dim titles2 = tempTitles2.Distinct().ToArray()
Dim titles2 = lestitres.Distinct().ToArray()
lestitres.Clear()
'For Each title As titlesclass In titles2
For Each letitre In query.Distinct
'ListBox.Items.Add(title) 'what you do with the values from here is up to you.
Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
Dim MyPic As New PictureBox
Dim MyLab As New Label
If (counter2 > 0 AndAlso ((counter2 Mod 4 = 0) OrElse counter3 = 1)) Then
counter3 = 1
counter4 += 1
If (counter2 Mod 4 = 0) Then
counter5 = 0
counter6 += 170
End If
MyPic.Location = New Point(counter5, MyPic.Location.Y + counter6)
MyLab.Location = New Point(counter5, MyPic.Location.Y + counter6)
If counter4 = 4 Then
counter3 = 0
End If
counter5 += 200
Else
MyPic.Location = New Point(counter, MyPic.Location.Y)
MyLab.Location = New Point(counter, MyPic.Location.Y)
End If
counter += 200
counter2 += 1
MyPic.SizeMode = PictureBoxSizeMode.AutoSize
MyLab.Text = letitre.Title
MyPic.Image = New System.Drawing.Bitmap(ImageStream)
Form2.Controls.Add(MyPic)
Form2.Controls.Add(MyLab)
Next
End Function
The class named titlesclass contain two elements which i will store my Link and Title in :
Public Class titlesclass
Public Property Link As String
Public Property Title As String
End Class
And My little button does all the work
Dim websiteURL1 As String = "http://www.gamestop.com/collection/upcoming-video-games"
Class1.getPics(websiteURL1, "<img src=""(?<Data>[^>]*)""><p>(?<Dataa>[^>]*)<br>")
What i'm trying to do is to show 4 pictureboxs per row with the lables right bellow each picture , for now some labels doesn't show , some shows just in the right place and some shows very far bellow ! I tested the values i'm getting with a Message Box and it shows me the informations in the order i need , i'm not sure if i screw up in the x,y values or if it's something else ...
Edit : I can already show the 4 pictureboxes per row , the labels also , but the Y of some labels isn't well adjusted it can go far far bellow !
Here is some pictures that will help you to understand my situation Don't mind the buttons and listboxs , it's just for the test :
My list containt a lot of pictures , so i just showed you some when the thing work kind of well , when it shows couple of rows far from the designed picture
http://img110.xooimage.com/files/f/a/d/picture1-5239f7c.png
http://img110.xooimage.com/files/8/f/8/picture-2-5239f7e.png
http://img110.xooimage.com/files/4/7/b/picture-3-5239f80.png
http://img110.xooimage.com/files/f/0/f/picture4-5239f82.png
So I cleaned the way you where generating the position of the PictureBox by using a row principle and increment:
Note:
If you need space at the top to add information start the row count at 1 instead of 0
Note 2:
Here the image dimensions are harcoded but you could use dynamic ones which would be more fluid. I just cleaned the positioning code not the rest.
Replace your function by this one:
Public Shared Sub getPics(website As String, pattern As String)
Dim tempTitles As New List(Of String)()
Dim tempTitles2 As New List(Of String)()
Dim lestitres As New List(Of titlesclass)
Dim webClient As New WebClient()
webClient.Headers.Add("user-agent", "null")
Dim counter As Integer = 0
Dim counter2 As Integer = 0
Dim counter3 As Integer = 0
Dim counter4 As Integer = 1
Dim counter5 As Integer = 0
Dim counter6 As Integer = 0
'If the website happens to go offline, at least your application wont crash.
'Handle default proxy
Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
proxy.Credentials = CredentialCache.DefaultCredentials
webClient.Proxy = proxy
Dim content As String = webClient.DownloadString(website)
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
Key .Title = title.Groups("Dataa").Value}
Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
Dim titles2 = lestitres.Distinct().ToArray()
lestitres.Clear()
'Count Items
Dim item As Integer = 0
'Count Row
Dim row As Integer = 0
'image: 222*122
For Each letitre In query.Distinct
Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
Dim MyPic As New PictureBox
Dim MyLab As New Label
'x = numéro item fois largeur image
'y = numéro de ligne fois hauteur image
MyPic.Location = New Point(item * 222, row * 122)
MyLab.Location = New Point(item * 222, row * 122)
MyPic.SizeMode = PictureBoxSizeMode.AutoSize
MyLab.Text = letitre.Title
MyPic.Image = New System.Drawing.Bitmap(ImageStream)
Form1.Controls.Add(MyPic)
Form1.Controls.Add(MyLab)
'Bring Labels to front
For Each ctrl As Control In Form1.Controls
'If the control is of type label
If TypeOf ctrl Is Label Then
'Then bring to front
ctrl.BringToFront()
End If
Next
'Increment the item count
item = item + 1
'If item is multiple of 4 or could check 4 then
If item Mod 4 = 0 Then
'Reset counter
item = 0
'Increment Row
row = row + 1
End If
Next
End Sub
Example return:

Throw ID and its information into listview

I got multiline textbox and ListView
textbox contains :
[1000]
name=John
number0=78569987
[1001]
name=Sara
number0=89768980
number1=77897545
TextBox2.Text = TextBox2.Text.Replace("[", "this what i want")
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
Dim FilterText = "this what i want"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
TextBox2.Lines = lines.ToArray
TextBox2.Text = TextBox2.Text.Replace("this what i want", "")
TextBox2.Text = TextBox2.Text.Replace("]", "")
ListBox1.Items.AddRange(TextBox2.Lines)
For Each x As String In ListBox1.Items
Dim II As New ListViewItem
II.Text = x
ListView1.Items.Add(II)
Next
I cant use the same way to insert numbers and names because some ids contain number0 number 1 and some contain only number 0 ,, so how can I insert their numbers ?
Thanks in advance.
Check the below code with comments. You might have to modify slightly to fit the data.
Check this question and it's linked questions for similar thing.
Edit: Note that this only copies from rows in richtextbox to different columns in listview, so it will work for the examples you provided. I hope you can refine this logic to account for specific columns as per the data coming in the richtextbox.
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
'Add 1st row to the listview
ListView1.Items.Add(New ListViewItem())
'Use Counter to determine row#
Dim j As Integer = 0
'Loop through the items
For i As Integer = 0 To lines.Count - 1
'Check if it's 1st item i.e. ID and add as text (i.e. at Index 0)
If lines(i).StartsWith("[") Then
ListView1.Items(j).Text = lines(i).Substring(1, lines(i).Length - 2)
'Check if contains other columns with attributes
ElseIf lines(i).Contains("=") Then
ListView1.Items(j).SubItems.Add(lines(i).Substring(lines(i).IndexOf("=") + 1))
'Check if it's an empty record, and add new row to listview
Else
j = j + 1
ListView1.Items.Add(New ListViewItem())
End If
Next

Adding records (Row/ Column) to DataGridView; Collection already belongs to a DataGridView control VB.NET

I'm looking for some help with an issue I am having.
I have multiple text files, in a folder. The folder can have an "unlimited" amount of text files in it, although typically 2-150 files
http://gyazo.com/5f314d1ca374abf9f813914609dd931d (images for this + below, can't embed due to lack of reputation)
Each file then contains an "unlimited" (although typically 0-20 lines) amount of data inside it. Line 1 being the "test number" and line 2 being the "test result" - as seen in the image above
My Data Grid View has 3 columns in it (Username, test number, test result) - as seen in the image above
When running my code below; first record being added to the Data Grid View works perfectly, but the second (or any record after the first) the error occurs:
http://gyazo.com/0d492b97d918853e62c55ee314f3f181 (image) or error message:
"System.InvalidOperationException: Collection already belongs to a
DataGridView control. This operation is no longer valid. at
System.Windows.Forms.DataGridViewCellCollection.Add(DataGridViewCelldataGridViewCell)
at SpellingBee.TeacherMultiResults.TeacherMultiResults_Load(Object
sender, EventArgs e)"
This error occurs on the DGVRow.Cells.Add(DGVCell) 'add cell to row
One thing I don't want to do is change any of my text file/ folder structures, even though I'm aware that it is currently inefficient storage.
How can I fix this error? I'm using VB.net (Visual Studios 2013)
If you need any more information, please just ask
Many thanks.
Imports System.Windows.Forms
Imports System.IO
Public Class TeacherMultiResults
Dim AmountOfFiles
Dim LineCount As Integer = 0
Dim FileName As IO.FileInfo
Dim DGVRow As New DataGridViewRow
Dim DGVCell As DataGridViewCell
Dim Username As String = ""
Dim TestNumber As Integer = 0
Dim TestResult As Integer = 0
Private Sub TeacherMultiResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim directory As New IO.DirectoryInfo(LoadForm.CurrentDirectory & "\UserResults\") 'selects directory
Dim FileNames As IO.FileInfo() = directory.GetFiles()
Dim Files As IO.FileInfo
For Each Files In FileNames 'list the names of all files in the specified directory
Username = Files.ToString
Username = (Username.Substring(0, Username.Length - 4)) 'removes the .txt from the name
Try
LineCount = File.ReadAllLines(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt").Length 'amount of lines in file
If LineCount > 1 Then
Dim Information As New System.IO.StreamReader(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt") 'opens file
LineCount = LineCount / 2 'halfs line count
For i = 0 To LineCount - 1
TestNumber = Information.ReadLine() 'reads line to variable
TestResult = Information.ReadLine() 'reads line to variable
i = i + 1 'adds one to i
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = Username 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestNumber 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestResult 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGV_MultiResults.Rows.Add(DGVRow) 'add row to DGV
Next
Information.Close() 'Close read
End If
Catch ex As Exception 'if file won't read
MsgBox(ex.ToString) 'show error
Exit Try
End Try 'end of try
Next 'end of files
End Sub
I hope that somebody can help me with this issue, I understand it's fairly simple to fix most probably although I can't seem to find a solution to the error!
Many thanks, Toby.
When working with a DataGridView, it is generally easier to just build an object list and then bind it to the DGV using the built-in data binding features.
For your example, it would look like this:
' Read the files, build objects as you go and add them to a list
Dim lst = New List(Of TeacherMultiResults)
' Replace this part with your file reading code...
Dim t1 = New TeacherMultiResults With {.Username = "Bob", .TestNumber = 1, .TestResult = 75}
lst.Add(t1)
Dim t2 = New TeacherMultiResults With {.Username = "Rick", .TestNumber = 1, .TestResult = 85}
lst.Add(t2)
Dim t3 = New TeacherMultiResults With {.Username = "Zoe", .TestNumber = 1, .TestResult = 95}
lst.Add(t3)
' Bind the list to the DataGridView
Dim bindList = New BindingList(Of TeacherMultiResults)(lst)
Dim bindSrc = New BindingSource
bindSrc.DataSource = bindList
grid.DataSource = bindSrc
Your grid should display each item of your list.

Trying to create text boxes dynammically and remove them

I am using VB.NET vb 2008 . I am trying to create text boxes dynammically and remove them here is the code i have written so far
Private Sub setTextBox()
Dim num As Integer
Dim pos As Integer
num = Len(word)
temp = String.Copy(word)
Dim intcount As Integer
remove()
GuessBox.Visible = True
letters.Visible = True
pos = 0
'To create the dynamic text box and add the controls
For intcount = 0 To num - 1
Txtdynamic = New TextBox
Txtdynamic.Width = 20
Txtdynamic.Visible = True
Txtdynamic.MaxLength = 1
Txtdynamic.Location = New Point(pos + 5, 0)
pos = pos + 30
'set the font size
Txtdynamic.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Txtdynamic.Name = "txtdynamic_" & intcount & "_mycntrl"
Txtdynamic.Enabled = False
Txtdynamic.Text = ""
Panel1.Controls.Add(Txtdynamic)
Next
Panel1.Visible = True
Controls.Add(Panel1)
Controls.Add(GuessBox)
Controls.Add(letters)
letter = ""
letters.Text = ""
hang_lable.Text = ""
tries = 0
End Sub`enter code here`
Function remove()
For Each ctrl In Panel1.Controls
Panel1.Controls.Remove(ctrl)
Next
End Function
I am able to create the textboxes but only a few of them are removed. by using For Each ctrl In Panel1.Controls it doesn't retrieve all the controls and some ae duplicated as well.
Change your remove to
Sub remove()
For i As Integer = Panel1.Controls.Count - 1 To 0 Step -1
Panel1.Controls.Remove(Panel1.Controls(i))
Next i
End Sub
If I am not mistaken you should not change a collection in a loop that you are currently looping, using a for each. The safest ways would be to use the index, in reverse, so that the position is not affected.