How to add csv file in a 2d array vb.net? - vb.net

User, 1,2,3,4,5,6,7,8,9
Joe, 34,3,32,1,3
John, 32,2
Tom, 98,34,23
Dave, 56, 53, 32,1,22,6,5
I have this csv file that I would like to put in a 2d array.
Private Sub GetElement()
'Read the data from the cv file
Try
Dim fileIn As String = "mel.csv"
Dim fileRows(), fileFields() As String
Dim count As Integer = 0
textBox.Text = String.Empty
If File.Exists(fileIn) Then
Dim fileStream As StreamReader = File.OpenText(fileIn)
fileRows = fileStream.ReadToEnd().Split(Environment.NewLine)
For i As Integer = 0 To fileRows.Length - 1
fileFields = fileRows(i).Split(",")
If fileFields.Length >= 2 Then
For x As Integer = 0 To fileFields.Length - 1
If x = 0 Then
For e As Integer = 0 To fileFields.Length
ele.Add(fileFields(e))
listBox.Items.Add(ele(e))
Next
End If
Next
count = count + 1
End If
Next
Else
textBox.Text = fileIn & " not found."
End If
Catch ex As Exception
textBox1.Text = ex.Message
End Try
End Sub
I was able to receive the first line only and then I have added it to a list box. In the MainWindow class I have declared two list of string to store the column and rows.

try this....
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder = "Path to your CSV folder (do not include the file name here)"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim dt As New DataTable
' change Test.csv to your csv file name here
Using Adp As New OleDbDataAdapter("select * from [Test.csv]", CnStr)
Try
Adp.Fill(dt)
Catch ex As Exception
End Try
End Using
DataGridView1.DataSource = dt
End Sub
End Class
this will import the CSV file then display it straight into a DataGridView control (list box has problem with columns)... hope that helps

Why don't you work with objects since you are working with an OO'programing language . It would be simple and more optimised if you created a new class . And then create a new object after reading each line . Dim u as new User(x,y,z...) And to organise your data, use a hashtable or a linkedlist (don't know if it's called like this for vb.net). Then you can fill in your listbox from objects that are in your hashtable or linkedlist.

Related

How to combine all csv files from the same folder into one data

I want merge multiple csv files with same layout from the same folder
example :
csv1.csv
ID, PINA,PINB,PCS
1,100,200,450
2,99,285,300
csv2.csv
ID, PINA,PINB,PCS
1,100,200,999
2,99,285,998
out.csv (The file I want make by VB.net)
ID, PINA,PINB,PCS,PCS
1,100,200,450,999
2,99,285,300,998
my problem code :
Dim FileReader As StreamReader
Dim i As Integer = 0
Dim temp As String
For i = 0 To LstFiles.Items.Count - 1
FileReader = File.OpenText(LstFiles.Items.Item(i))
temp = FileReader.ReadToEnd
File.AppendAllText(SaveFileDialog1.FileName, temp)
Next
Please guide me.
Thanks a lot !
Looks to me like each line in the input files has an identifier based on the first value in that row. You want to combine all the numbers after that identifier, from all the files in your ListBox, into one list of numbers that is sorted and has no duplicates. Then you want to generate an output file that has all those identifiers followed by each set of sorted, unique numbers.
If that is correct, then try this out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
Dim header As String = ""
Dim combinedLines As New SortedList(Of Integer, List(Of Integer))
For Each filename As String In LstFiles.Items
Dim lines = File.ReadLines(filename)
If header = "" Then
header = lines.First
End If
lines = lines.Skip(1)
For Each line As String In lines
Dim strValues = line.Split(",").AsEnumerable
Try
Dim lineNumber As Integer = Integer.Parse(strValues.First)
strValues = strValues.Skip(1)
Dim numbers = strValues.ToList.ConvertAll(Of Integer)(Function(x) Integer.Parse(x))
If Not combinedLines.ContainsKey(lineNumber) Then
combinedLines.Add(lineNumber, New List(Of Integer)(numbers))
Else
combinedLines(lineNumber).AddRange(numbers)
End If
Catch ex As Exception
MessageBox.Show("Error Parsing Line: " & line)
End Try
Next
Next
Using sw As New StreamWriter(SaveFileDialog1.FileName, False)
sw.WriteLine(header)
For Each numberSet In combinedLines
Dim numbers = numberSet.Value.Distinct.ToList
numbers.Sort()
sw.WriteLine(numberSet.Key & "," & String.Join(",", numbers))
Next
End Using
End If
End Sub

Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

I have the following requirement,
I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.
(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.
(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.
Am I missing something here or is it like that? Any advice will be highly appreciated.
Im filling it in runtime using a procedure.
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
cmbDisProfile.DataSource = tempTb
cmbDisProfile.DisplayMember = "discount_profile"
End Sub
Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.
My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.
Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)
Return fetchedDataTable
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)
Dim SqlCmd As New SqlCommand(sqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
dataAdapter.Update(tbToUpdate)
End Sub
Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
Try
Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"
'Dim searchString As String = txtCategoryCode.Text
' searchOwnerCmd.Parameters.Clear()
' searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(searchSql)
If tempTb.Rows.Count = 0 Then
Return False
Else
Return True
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)
Return fetchedSearchTB
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].
How do you fill/populate your ComboBox with Data From Database Table ?
In this link, Microsoft docs state, that:
Use the SelectedIndex property to programmatically determine the index
of the item selected by the user from the DropDownList control. The
index can then be used to retrieve the selected item from the Items
collection of the control.
In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.
proposed,
ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"
does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
Dim i As Integer = 0
For i = 0 To tempTb.Rows.Count - 1
cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
Next
End Sub
After adding we can use the following code to display the data on combobox (DropDownList).
Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
Try
Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
If Len(txtItCode.Text) < 4 Then
cmdAdd.Enabled = False
cmdDelete.Enabled = False
cmdSave.Enabled = False
Else
If tempTb.Rows.Count > 0 Then
With tempTb
txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
End With
cmdAdd.Enabled = False
cmdDelete.Enabled = True
cmdSave.Enabled = True
Else
cmdAdd.Enabled = True
cmdDelete.Enabled = False
cmdSave.Enabled = False
txtItName.Text = ""
Call fillItCategories()
Call fillProProfile()
Call filldisProfiles()
Call fillFinCat()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

datagridview Image Display vb.net MS Access

my code is to read the image file path in every row and display it in the datagridview "Image" Column.
.....
what's the problem with my code? please help me fix this.
UPDATE
this is the updated code but it displays nothing.
Dim dbdataset As New DataTable
Try
con.Open()
query = "Select * FROM [svfmemberlist]"
cmd = New OleDbCommand(query, con)
da.SelectCommand = cmd
da.Fill(dbdataset)
dgvSearch.RowTemplate.Height = 150
source.DataSource = dbdataset
dgvSearch.DataSource = source
Dim img As New DataGridViewImageColumn()
dgvSearch.Columns.Add(img)
img.HeaderText = "Image"
img.Name = "img"
img.ImageLayout = DataGridViewImageCellLayout.Zoom
dgvSearch.Columns("img").DataGridView.AutoGenerateColumns = False
dgvSearch.Columns("Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
dgvSearch.Columns("img").Width = 150
For Each row As DataGridViewRow In dgvSearch.Rows
If Not row.Cells("imgPath").FormattedValue.ToString = Nothing Then
Dim str As String = row.Cells("imgPath").FormattedValue.ToString
Dim inImg As Image = Image.FromFile(str)
row.Cells("img").Value = inImg
Else
img.Image = Nothing
End If
Next
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
The following example does not match how you are loading data and images but with a little effort will work within your current code.
I created two columns in the DataGridView via the IDE, one Text and one Image DataGridViewColumn.
The first line in form load sets ImageLayout, second line of code sets alignment to top-left for appearances. Next I set auto-size mode for all columns followed by setting the row height for each row.
Next (these lines are to load images from a folder one level below the app folder).
Setup the path to the images.
Add images using FileImageBytes function (which I would place into a separate class or code module but works just fine in your form).
Yes everything is hard-wired so it's easy to see how everything works.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CType(DataGridView1.Columns("PictureColumn"), DataGridViewImageColumn).ImageLayout = DataGridViewImageCellLayout.Normal
DataGridView1.Columns.Cast(Of DataGridViewColumn).Select(Function(col) col).ToList _
.ForEach(Sub(col) col.CellTemplate.Style.Alignment = DataGridViewContentAlignment.TopLeft)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
DataGridView1.RowTemplate.Height = 222
Dim imagePath As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")
DataGridView1.Rows.Add(New Object() {"Car1", FileImageBytes(IO.Path.Combine(imagePath, "Car1.bmp"))})
DataGridView1.Rows.Add(New Object() {"Car2", FileImageBytes(IO.Path.Combine(imagePath, "Car2.jpg"))})
End Sub
Public Function FileImageBytes(ByVal FileName As String) As Byte()
Dim fileStream As IO.FileStream = New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim byteArray(CInt(fileStream.Length - 1)) As Byte
fileStream.Read(byteArray, 0, CInt(fileStream.Length))
Return byteArray
End Function
End Class

Unable to cast object of type 'System.Data.DataTable' to type 'System.Collections.IEnumerable'

So I created an object called Report. A Report object has several different properties, including a DataSet. This DataSet is supposed to contain at least one DataTable. Report is serializable. In a Unit Test I instantiate a Report object, give its properties values, then serialize it, then deserialize it.
After adding a method to populate the DataSet, the Deserialization function gives me Error: Unable to cast object of type 'System.Data.DataTable' to type 'System.Collections.IEnumerable'.
Shouldn't it be getting serialized as a DataSet...not a DataTable? I'm not sure exactly what is causing me this error. Code snippets are below. Any help is appreciated!
<Serializable> Public Class Report
Private titleStr As String
Private startDateTime As DateTime
Private endDateTime As DateTime
Private numIntervalsShort As Short
Private binnedDataSet As DataSet
...property gets and sets...namely:
Property BinnedData As DataSet
Get
Return binnedDataSet
End Get
Set(ByVal value As DataSet)
binnedDataSet = value
End Set
End Property
End Class
<TestClass()> Public Class ReportObjectTest
<TestMethod()> Public Sub TestCreateReport()
Dim testReport As New Project.Report
testReport.Title = "Test Title"
testReport.StartDate = "1/1/2015 1:00 AM"
testReport.EndDate = "1/2/2015 6:00 PM"
testReport.NumIntervals = 41
PopulateDataSet(testReport)
Serialize(testReport)
Deserialize()
End Sub
Private Sub PopulateDataSet(ByRef report As Project.Report)
report.BinnedData = New DataSet()
Dim DT1 As DataTable = New DataTable("Test Table1")
report.BinnedData.Tables.Add(DT1)
DT1.Columns.Add(New DataColumn("Column1", GetType(Int32)))
DT1.Columns.Add(New DataColumn("Column2", GetType(Int32)))
DT1.Columns.Add(New DataColumn("Column3", GetType(Int32)))
Dim Row1 As DataRow = DT1.NewRow()
Dim Row2 As DataRow = DT1.NewRow()
Dim Row3 As DataRow = DT1.NewRow()
Row1("Column1") = 32
Row1("Column2") = 15
Row1("Column3") = 9
Row2("Column1") = 3
Row2("Column2") = 27
Row2("Column3") = 98
Row2("Column1") = 1
Row2("Column2") = 12
Row2("Column3") = 65
End Sub
Private Sub Serialize(ByRef report As Project.Report)
Dim stream As New FileStream("TestReport.xxx", FileMode.Create)
Dim mySerializer As BinaryFormatter = New BinaryFormatter()
Try
mySerializer.Serialize(stream, report)
Catch ex As SerializationException
Console.WriteLine("Error saving the report. " & ex.Message)
Throw
Finally
stream.Close()
End Try
End Sub
Private Sub Deserialize()
Dim readTestReport As New Project.Report()
Dim stream As New FileStream("TestReport.xxx", FileMode.Open)
Dim myDeserializer As BinaryFormatter = New BinaryFormatter()
Try
readTestReport = DirectCast(myDeserializer.Deserialize(stream), Project.Report)
Catch ex As SerializationException
Console.WriteLine("Error opening the report. " & ex.Message)
Throw
Finally
stream.Close()
End Try
Console.WriteLine(Environment.NewLine & "Values after Deserialization:")
Console.WriteLine("Title = " & readTestReport.Title)
Console.WriteLine("Start Date = " & readTestReport.StartDate)
Console.WriteLine("End Date = " & readTestReport.EndDate)
Console.WriteLine("Number of Intervals = " & readTestReport.NumIntervals)
For Each Table In readTestReport.BinnedData.Tables
For Each Row In Table
Console.WriteLine("Table Row = " & Row.ToString)
For Each DataColumn In Row
Console.WriteLine(DataColumn.ToString)
Next
Next
Next
End Sub
End Class
I was right...figured it out. The issue lay in how I was trying to display the values of the table after deserializing. DataTables and DataRows are not enumerable, but the way I was trying to display it was by looping through the way you only can with an enumerable type.
I modified that block to assign the table to a View instead:
Dim tableView As DataView = New DataView(readTestReport.BinnedData.Tables(0))
Console.WriteLine("Table = ")
Dim rowView As DataRowView
Dim i As Integer
For Each rowView In tableView
For i = 0 To tableView.Table.Columns.Count - 1
Console.Write(rowView(i) & vbTab)
Next
Console.WriteLine()
Next
These articles helped:
https://msdn.microsoft.com/en-us/library/23a0aths%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/bb669099%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Visual Basic How to add a Destinct Combobox from a comma-delimited file instead of a database?

delimited files what i need is to read from a comma-delimited file and retrieve ownley certain lines off them to a combobox, the combobox must then ownley show destinct names. I added a database-working code below of what im looking for but instaed of using a database i need the code for comma-delimeted files.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call combo1()
End Sub
Sub combo1()
Dim com As SqlConnection
com = New SqlConnection("Server = Q-DESIGN\SQLEXPRESS; Database = Q-Design Test Results; Trusted_Connection = true;")
com.Open()
Dim command As SqlCommand = New SqlCommand("SELECT DISTINCT(Testname) from URL", com)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
ComboBox1.Items.Add(reader.GetString(0))
End While
reader.Close()
com.Dispose()
com.Close()
End Sub
My comma delimited file will have the following lines for egsample
Jenny, 25, Female
Micheal, 100, Female
shaun, 50, male
Cindy, 75, Female
Cindy, 30, Female
Cindy, 20, Female
Micheal, 30, Female
deric, 50, Male
I need the combobox to show every name, ownley once
You can use a TextFieldParser and a HastSet.
Here's a simple example:
' a set to store the names
Dim names = new HashSet(Of String)
Using reader = New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\your\path")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
' read rows and add first field to set
currentRow = reader.ReadFields()
names.Add(currentRow(0).ToString())
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
' do something
End Try
End While
End Using
' bind data to combo box (or use Items.Add instead)
comboBox.DataSource = names.ToList()
First I would read in the file one line at a time. I would then use regular expressions to extract the name field your looking for. Next I would add each item to a SortedSet.
Dim strLine as String = ""
Dim RX as New Regex("^([^,]*),")
Dim MyMatch as Match
Dim NameLookup as New SortedSet(Of String)
'
' Code to read in each line into strLine using StreamReader.
'
MyMatch = RX.Match(strLine)
If MyMatch.Success AndAlso Not NameLookUp.Contains(MyMatch.Result("${1}")) Then
NameLookup.Add(MyMatch.Result("${1}"))
End If
After this adding the items from the SortedSet to the ComboBox should be fairly easy.
Also you can also manually create a DataTable with a "Name" column and use data bindings
to automatically populate the combobox.