2016-05-07 2 views
0

Мне нужно импортировать информацию из файла CSV txt в базу данных с помощью DataGridView в моей форме. Приложение должно позволить пользователю открыть .txt-файл, а затем обновить таблицу DataGridView в моей форме. Я могу получить файл, но не могу обновить сетку с помощью файла. Я могу обновлять текстовые поля, но не могу понять, как обновить сетку. Может ли кто-нибудь помочь мне с этим?Импорт CSV-файла в базу данных с помощью VB

Imports Microsoft.VisualBasic.FileIO 
Imports System.IO 

Public Class Form1 
Private fileToOpen As String    'the file to be opened and read 
Private responseFileDialog As DialogResult 'response from OpenFileDialog 
Private myStreamReader As StreamReader  'the reader object to get contents of file 
Private myStreamWriter As StreamWriter  'the writer object to save contents of textbox 
Private myTextFieldParser As TextFieldParser ' To parse text to searched. 
Dim myDataAdapter As OleDb.OleDbDataAdapter 
Dim myString() As String 
Dim myRow As DataRow 



Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click 
    Me.Validate() 
    Me.PeopleBindingSource.EndEdit() 
    Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet) 

End Sub 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed. 
    Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People) 

End Sub 

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click 
    Dim fileContentString As String   'contents of the file 
    Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter) 
    'Dim myRow As DataRow 

    'set the properties of the OpenFileDialog object 
    OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory 
    OpenFileDialog1.Title = "Select File to View..." 
    OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*" 


    'responseFileDialog contains holds the response of the user (which button they selected) 
    responseFileDialog = OpenFileDialog1.ShowDialog() 

    'check to see if the user select OKAY, if not they selected CANCEL so don't open anything 
    If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then 
     'make sure there isn't a file already open, if there is then close it 
     If (myStreamReader IsNot Nothing) Then 
      myStreamReader.Close() 
      'TextBoxFileOutput.Clear() 
     End If 

     'open the file and read its text and display in the textbox 
     fileToOpen = OpenFileDialog1.FileName 
     myStreamReader = New StreamReader(OpenFileDialog1.FileName) 

     initTextFieldParser() 

     'loop through the file reading its text and adding it to the textbox on the form 
     Do Until myStreamReader.Peek = -1 
      fileContentString = myStreamReader.ReadLine() 

      'Try 
      ' myTextFieldParser = New TextFieldParser(fileToOpen) 
      ' myTextFieldParser.TextFieldType = FieldType.Delimited 
      ' myTextFieldParser.SetDelimiters(",") 
      'Catch ex As Exception 
      ' MessageBox.Show("Cannot Open File to Be Read!") 
      'End Try 


      myTextFieldParser.TextFieldType = FieldType.Delimited 

      myString = TextFieldParser.NewLine() 

      myRow.Item("FirstName") = myString(1) 

      MyContactsDataSet.Tables("People").Rows.Add(myRow) 
      PeopleTableAdapter.Update(MyContactsDataSet) 
      'TextBoxFileOutput.AppendText(fileContentString) 
      'TextBoxFileOutput.AppendText(Environment.NewLine) 
     Loop 

     'close the StreamReader now that we are done with it 
     myStreamReader.Close() 
     'SaveToolStripMenuItem.Enabled = True 
    End If 
End Sub 

Private Sub initTextFieldParser() 
    'Close myTextFieldParser in case the user is surfing through the records and then 
    'decides to search for a particular last name --> Basically  start searching from beginning of the file 
    If (myTextFieldParser IsNot Nothing) Then 
     myTextFieldParser.Close() 
    End If 

    Try 
     myTextFieldParser = New TextFieldParser(fileToOpen) 
     myTextFieldParser.TextFieldType = FieldType.Delimited 
     myTextFieldParser.SetDelimiters(",") 
    Catch ex As Exception 
     MessageBox.Show("Cannot Open File to Be Read!") 
    End Try 
End Sub 
End Class 
+0

Можете ли вы предоставить код, который вы пробовал до сих пор и не работает? – Spidey

+0

Я только что отказался от него и начал все заново. Я скоро поставлю то, что у меня есть. Спасибо!! – Magdalina08

+0

МНОГИЕ недостающие детали. Если пользователь должен иметь возможность редактировать/просматривать данные * до * сохранения, проанализировать данные на пустой (типизированный) DataTable и связать их с DGV. Используйте что-то вроде TextFieldParser, OleDB или CSVHelper для синтаксического анализа текстового файла csv. Циллионы вопросов здесь о том, как, – Plutonix

ответ

0

обновление GridView с содержимым файла

Импорт System.IO, как мы будем нуждаться в StreamReader

Using reader As New StreamReader("filepath") 
    DataGridView1.Columns.Add("col1",reader.ReadToEnd()) 
End Using 

проверить это out!