First row as header in datagridview - vb.net

Imported data from CSV to datagridview has header in first row, I could hide that row and name header for every column, problem is that data table has 68 columns. Is it possible to make first row header without having to do that manually for every single column?

Your datagrid should have taken all column names from CSV, if not then you need to have a look at this great article. It will help you a lot. This is the link.

After experimenting and help from user: ooopsoft :
Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(receiveStream)
TextFieldParser1.Delimiters = New String() {","}
Dim newline() As String = TextFieldParser1.ReadFields()
While Not TextFieldParser1.EndOfData
Dim Row1 As String() = TextFieldParser1.ReadFields()
If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
Dim i As Integer
For i = 0 To Row1.Count - 1
DataGridView1.Columns.Add(newline(i), newline(i))
Next
End If
End While

Related

Selecting specific columns while writing it to CSV file

I am writing a CSV file using a dataset. I need to only select few columns from my dataset not all the columns.
I am using below code but it's writing all the columns in the data row to CSV file.
I need to write only first, third and fifth columns to the CSV file and ignore second and fourth columns.
For Each row As DataRow In dsRefs.Tables(0).Rows
For i As Integer = 0 To dsRefs.Tables(0).Columns.Count() -
csvWriter.NextRecord()
Next
Next
A technique to resolve this might be;
Dim listOfColums = (From dtR As DataRow In dsRefs.Tables(0).Rows
Select r1 = dtR.Item(0), 'first
r2 = dtR.Item(2), 'third
r3 = dtR.Item(4)) 'fifth
Using sWriter As StreamWriter = New StreamWriter("C:\YouurPathToSaveCsv\YourFileCsv.csv")
Dim divider As String = ";"
If listOfColums IsNot Nothing AndAlso listOfColums.Count > 0 Then
For Each okList In listOfColums
Dim cRow As String = Strings.Join({okList.r1, okList.r2, okList.r3}, divider)
Console.WriteLine(cRow)
sWriter.WriteLine(cRow)
Next
End If
End Using

How to format textfiles values retrieved from a directory and displayed in datagridview in vb.net

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.

VB.net deleting row from DT

I have the below code which works fine, although I want it to only delete the row if the whole row is empty. At the moment if there is no text in the first column it deletes the row even though there maybe text in the other columns.
Also want to trim the text as sometimes there are spaces in the columns with no text. this will ensure that blank rows are deleted.
Any help is greatly appreciated.
Thanks
For i As Integer = dt.Rows.Count - 1 To 0 Step -1
Dim row As DataRow = dt.Rows(i)
If row.Item(0) Is Nothing Then
dt.Rows.Remove(row)
ElseIf row.Item(0).ToString.Trim = "" Then
dt.Rows.Remove(row)
End If
Next
You are deleting the rows from just a datatable not from database.
Below code could help you.
Dim valuesarr As String = String.Empty
For i As Integer = 0 To dt.Rows.Count - 1
Dim lst As New List(Of Object)(dt.Rows(i).ItemArray)
For Each s As Object In lst
valuesarr &= s.ToString 'can use trim here if you want to delete spaces
Next
If String.IsNullOrEmpty(valuesarr) Then
'Remove row here, this row do not have any value
dt.Rows(i).Remove()
End If
Next

Listview data to another Listview

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

Adding two column values to listbox in vb.net

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