I have a line of text A;B;C;D; in a text file. what I'm wanting to achive is to populate a combobox so that it reads as follows
A
B
C
D
Using the ; char as a way to define a new combobox entry.
its supose to work in combination with the following code...
For Each line As String In IO.File.ReadAllLines("C:\TEST.txt")
If line.StartsWith("+dep+") Then
ComboBox1.Text = line.Substring(5)
End If
which selects a tag from a file with alsorts of stored data (in this case the +dep+ tag and usses this to populate the combobox)...
dose anyboy know how?
I'm ussing vb.net
So you want to take the text after <dep> and split it by ;? Then poulate a combobox with all parts:
Dim lineParts = From line In File.ReadLines(path)
Let depIndex = line.IndexOf("<dep>")
Where depIndex >= 0
Select line.Substring(depIndex + 5).Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
Dim allParts = lineParts.SelectMany(Function(p) p)
Dim bs = new BindingSource()
bs.DataSource = allParts
ComboBox1.DataSource = bs
If you want unique items only you just have to add Distinct:
Dim allParts = lineParts.SelectMany(Function(p) p).Distinct()
Related
I'm using the VB.net forms application for this project.
so I have a text file like this
7,John,Kimberlake,john#mail.com,27,Bachelor
8,Tiny,Down,tiny#mail.com,34,Master
9,Jeniffer,Kime,Jen#mail.com,22,None
I have 1 textbox and 1 button.
The purpose is that you need to fill an id number to find the data about the person.
Dim Findstring = IO.File.ReadAllText("data.txt")
Dim Data As String = TextBox1.Text
Dim aryTextFile() As String
aryTextFile = Findstring.Split(",")
If aryTextFile.Contains(Data) Then
End If
I tried this and something like finding the index number in the array of the requested id but it didn't work.
Instead of ReadAllText use ReadLines and loop each line to get the data.
Walk through below code and comments.
There are much better ways to do this, But the below is very basic way of doing for easy understanding.
'READ EACH LINE OF THE TEXT FILE.
For Each item As String In IO.File.ReadLines("C:\\Desktop\\test.txt") 'ENSURE VALID PATH HERE
'THIS IS EACH LINE.
Dim Findstring = item
'ASSUME THIS IS TEXT ID FROM TEXT BOX.
Dim ID As String = "8"
'SPLIT THE LINE BASED ON ","
Dim aryTextLine() As String
aryTextLine = Findstring.Split(",")
'NOW YOU HAVE ARRAY TO READ EACH ITEM.
If aryTextLine(0) = ID Then
Dim name = aryTextLine(1)
End If
Next
The problem now is how would I be able to format the values being displayed in datagridview from textfiles.
I have retrieved values from looping through textfiles removed the first two strings. Now I want to add separators or change the format of the displayed value like, for example:
textfile lines: result:
01Sample - line1
022 - line2
0306212019 - line3 06/21/2019
041234567890 - line4 12,345,678.90
I have already tried this one changing the defaultcellstyle but since the values are from textfiles in a directory its not affecting the output
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
Private Sub ReadTextFiles()
Dim dt As New DataTable
dt.Columns.Add("Date")
dt.Columns.Add("Gross Sales")
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
lstLines.AddRange(File.ReadAllLines(fileentries))
Next
Dim i As Integer
Dim OuterLoopIterations As Integer = CInt(lstLines.Count / 22)
For iterations = 0 To OuterLoopIterations - 1
Dim row = dt.NewRow
For col = 0 To 21
row(col) = lstLines(i).Remove(0, 2) 'i have removed the first 2 characters of each string
i += 1
Next
dt.Rows.Add(row(2), row(5), row(12), row(13), row(14), row(15), row(7), row(8), row(11))
Next
DataGridView1.DataSource = dt
'the code i tried applying
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
this is my expected result
Current datagrid view:
the result should be for date column: 06/07/2019
for the gross : 48,990.14
Edit:
I tried this one
Dim B As Double
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
B = CDbl(Val(fileentries))
lstLines.AddRange(File.ReadAllLines(B))
Next
If you want to format something as a number then it has to be a number. That means that, for example, if you read the text "1234.5" from the file and you want to display it as 1,234.50 in your grid then you have to convert the String you read to a Double or Decimal. If you do that then the numeric format specifier you're using in the grid column will work.
I have two listview controls, each having the same column headers. Listview1 contains the master data table and listview2 has a much smaller set of data that I need to add to the Master in Listview1. I can add this new data to the bottom of the main data in Listview1 using the AddRange option, but I need to add it to the top of the data in Listview1 but cannot see how.
If anyone can help I would appreciate it. Thank you in advance.
Thank you for your comments, which I have taken on board.
Let me add some more detail and some code. The data in Listview2 is a monthly csv file input which I read into the Listview2. The data is a set of details with the first field being the date, the most recent date at the top of data. I package this data as an array and attempt to load in into listview1, the master file, with the exact same fields and date order. Here is the code I have used to load the csv and the code to place the packaged data into Listview1. The only problem with this is, it places the data at the end of the current file in Listview1, so it would be out of sequence, so I am trying to place it at the top of the current file in Listview1.
' load the file into listview with this quick routine.
Dim CSVTest As List(Of String) = New List(Of String)
CSVTest = File.ReadAllLines(ImportDirname).ToList
Dim ColNames As List(Of ColumnHeader) = New List(Of ColumnHeader)
Dim ColumnArray() As String = CSVTest(0).Split(",")
For i = 0 To ColumnArray.Count - 1
ColNames.Add(New ColumnHeader)
ColNames(i).Name = ColumnArray(i)
ColNames(i).Text = ColumnArray(i)
Next
ListView2.Columns.AddRange(ColNames.ToArray)
'This adds the rest of the data from the file to the listview.
For I = 1 To CSVTest.Count - 1
Dim col() As String = CSVTest(I).Split(",")
Dim NewLVItem As ListViewItem = New ListViewItem(col(0))
NewLVItem.Name = col(0)
For j = 1 To col.Count - 1
NewLVItem.SubItems.Add(col(j))
Next
ListView2.Items.Add(NewLVItem)
Next (I)
' this adds the range to the bottom of the listview data
' - not what is required. I need it at the top !!!!!
Dim Items(ListView2.Items.Count - 1) As ListViewItem
For i As Integer = 0 To ListView2.Items.Count - 1
Items(i) = CType(ListView2.Items(i).Clone, ListViewItem)
Next
ListView1.Items.AddRange(Items)
Again if anyone can help I would be grateful.
Try Something Like This
With lst1. Items.**Insert**(0, "Sample", 0)
.SubItems.Add(2)
.SubItems.Add(3)
.SubItems.Add(4)
.SubItems.Add(5)
.SubItems.Add(6)
.SubItems.Add(listDownload.Count - 1)
End With
Hope this can help you
Update 5/21/17. Thank you for the suggestion of using a Table. That was helpful. I actually figured it out. I made myinputable a global variable by declaring the Dim statement at the top and making it a Datagridview type. Now I can turn it off in the other event that I needed to do it.
I am a novice. I have created a Datagridview in VB 2015 to capture a bunch of data from the use. When the user is finished with the data entry, I want to store the cell values in my variables. I do not know how to capture any event from my dynamically created datagridview "myinputable." My code is below. Please help.
Private Sub inputmodel()
Dim prompt As String
Dim k As Integer
'
' first get the problem title and the number of objectives and alternatives
'
prompt = "Enter problem title: "
title = InputBox(prompt)
prompt = "Enter number of criteria: "
nobj = InputBox(prompt)
prompt = "Enter number of alternatives: "
nalt = InputBox(prompt)
'
' now create the table
'
Dim Myinputable As New DataGridView
Dim combocol As New DataGridViewComboBoxColumn
combocol.Items.AddRange("Increasing", "Decreaing", "Threashold")
For k = 1 To 6
If k <> 2 Then
Dim nc As New DataGridViewTextBoxColumn
nc.Name = ""
Myinputable.Columns.Add(nc)
Else
Myinputable.Columns.AddRange(combocol)
End If
Next k
' now add the rows and place the spreadsheet on the form
Myinputable.Rows.Add(nobj - 1)
Myinputable.Location = New Point(25, 50)
Myinputable.AutoSize = True
Me.Controls.Add(Myinputable)
FlowLayoutPanel1.Visible = True
Myinputable.Columns(0).Name = "Name"
Myinputable.Columns(0).HeaderText = "Name"
Myinputable.Columns(1).Name = "Type"
Myinputable.Columns(1).HeaderText = "Type"
Myinputable.Columns(2).Name = "LThresh"
Myinputable.Columns(2).HeaderText = "Lower Threshold"
'Myinputable.Columns(2).ValueType = co
Myinputable.Columns(3).Name = "UThresh"
Myinputable.Columns(3).HeaderText = "Upper Threshold"
Myinputable.Columns(4).Name = "ABMin"
Myinputable.Columns(4).HeaderText = "Abs. Minimum"
Myinputable.Columns(5).Name = "ABMax"
Myinputable.Columns(5).HeaderText = "Abs. Maximum "
Myinputable.Rows(0).Cells(0).Value = "Help"
If Myinputable.Capture = True Then
MsgBox(" damn ")
End If
End Sub
As #Plutonix suggests, you should start by creating a DataTable. Add columns of the appropriate types to the DataTable and then bind it to the grid, i.e. assign it to the DataSource of your grid, e.g.
Dim table As New DataTable
With table.Columns
.Add("ID", GetType(Integer))
.Add("Name", GetType(String))
End With
DataGridView1.DataSource = table
That will automatically add the appropriate columns to the grid if it doesn't already have any, or you can add the columns in the designer and set their DataPropertyName to tell them which DataColumn to bind to. As the user makes changes in the grid, the data will be automatically pushed to the underlying DataTable.
When you're done, you can access the data via the DataTable and even save the lot to a database with a single call to the Update method of a data adapter if you wish.
I have a table named users which has the following columns in it
User_id,user_name,user_pwd,First_Name,Middle_Name,Last_Name and user_type.
I have dataset named dst and created a table called user in the dataset. Now I want to populate listbox with user_Name, First_Name, Last_name of each and every row in the table user.
I am able to add one column value at a time but not getting how to add multiple column values of each row to listbox
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(row("User_Name"))
Next
Above code works perfectly but I also want to add First_name as well as last_name to the list box at the same time.
Use same approach as you have, but put all values you want in one string.
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
Dim sItemTemp as String
sItemTemp = String.Format("{0},{1},{2}", row("User_Name"), row("First_Name"), row("Last_Name"))
lstUsers.Items.Add(sItemTemp)
Next
String.Format() function will call .ToString() on all parameters.
In this case if row(ColumnName) is NULL value then .ToString() return just empty string
You have 2 choices:
Using the ListBox:
To use the ListBox, set the font to one that is fixed width like courier new (so that the columns line up), and add the items like this:
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(RPAD(row("User_Name"),16) & RPAD(row("First_Name"),16) & RPAD(row("Last_Name"),16))
Next
The RPAD function is defined like this:
Function RPAD(a As Object, LENGTH As Object) As String
Dim X As Object
X = Len(a)
If (X >= LENGTH) Then
RPAD = a : Exit Function
End If
RPAD = a & Space(LENGTH - X)
End Function
Adjust the LENGTH argument as desired in your case. Add one more for at least one space. This solution is less than ideal because you have to hard-code the column widths.
Use a DataGridView control instead of a ListBox. This is really the best option, and if you need, you can even have it behave like a ListBox by setting the option to select the full row and setting CellBorderStyle to SingleHorizontal. Define the columns in the designer, but no need to set the widths - the columns can auto-size, and I set that option in the code below. if you still prefer to set the widths, comment out the AutoSizeColumnsMode line.
The code to set up the grid and add the rows goes like this:
g.Rows.Clear() ' some of the below options are also cleared, so we set them again
g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells
g.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal
g.SelectionMode = DataGridViewSelectionMode.FullRowSelect
g.AllowUserToAddRows = False
g.AllowUserToDeleteRows = False
g.AllowUserToOrderColumns = True
For Each row As DataRow In dt.Rows
g.Rows.Add(row("User_Name"), row("First_Name"), row("Last_Name"))
Next
You might solved your problem by now but other users like me might have issue with it.
Above answers given worked for me even but I found a same answer in a simple way according to what I want..
cmd = New SqlCommand("select User_Name, First_Name, Last_Name from User")
Dim dr As SqlDataReader = cmd.ExecuteReader(YourConnectionString)
If dr.HasRows Then
Do While dr.Read
lst.Items.Add(dr.Item(0).ToString & " " & dr.Item(1).ToString & " " & dr.Item(2).ToString)
Loop
End If
This worked for me, maybe wrong way but I found it simple :)
May I suggest you use a ListView control instead of Listbox?
If you make the switch, here's a sample subroutine you could use to fill it up with the data you said you want. Adapt it the way you like; there's much room for improvement but you get the general idea:
Public Sub FillUserListView(lstUsers As ListView, Dst As DataSet)
Dim columnsWanted As List(Of String) = New List(Of String)({"User_Name", "First_Name", "Last_Name"})
Dim dt As DataTable = Dst.Tables("user")
Dim columns As Integer = 0
Dim totalColumns = 0
Dim rows As Integer = dt.Rows.Count
'Set the column titles
For Each column As DataColumn In dt.Columns
If columnsWanted.Contains(column.ColumnName) Then
lstUsers.Columns.Add(column.ColumnName)
columns = columns + 1
End If
totalColumns = totalColumns + 1
Next
Dim rowObjects(columns - 1) As ListViewItem
Dim actualColumn As Integer = 0
'Load up the rows of actual data into the ListView
For row = 0 To rows - 1
For column = 0 To totalColumns - 1
If columnsWanted.Contains(dt.Columns(column).ColumnName) Then
If actualColumn = 0 Then
rowObjects(row) = New ListViewItem()
rowObjects(row).SubItems(actualColumn).Text = dt.Rows(row).Item(actualColumn)
Else
rowObjects(row).SubItems.Add(dt.Rows(row).Item(actualColumn))
End If
lstUsers.Columns.Item(actualColumn).Width = -2 'Set auto-width
actualColumn = actualColumn + 1
End If
Next
lstUsers.Items.Add(rowObjects(row))
Next
lstUsers.View = View.Details 'Causes each item to appear on a separate line arranged in columns
End Sub