none
IMPORT TEXT FILE TO DATAGRIDVIEW RRS feed

  • Question

  • HI

    I have a number undefined of TEXTFILE
    Take the following format 

    ------------------------------------------------------------------------------------------------------ | WESITESERVER_ID | WESITESERVER_CODE | WESITESERVER_NAME | WESITESERVER_URL | ------------------------------------------------------------------------------------------------------


    The files comes from exporting access tables to text files

    I want every file to take a row in the DataGrid View

    Keeping in mind that files are different cells and number after interval "|"

    Note the first column in the datagridview takes the name of the text file

    Wednesday, September 26, 2018 9:18 AM

Answers

  • @rguy72, why did you post C# in this forum which is for VB.NET ? The person asking for assistance has a history with VB.NET, not C#.

    Please revise to VB.NET or remove your reply.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by ahmeddc Sunday, December 2, 2018 2:01 AM
    Monday, November 26, 2018 3:17 AM
    Moderator

All replies

  • I would suggest using a TextFieldParser, set Delimiter property to |. Cycle through the file, if a line when split (see example from first link) there are more than one element (there would not be for lines with only dashes) then use the elements/fields to populate the DataGridView. You of course have to consider the beginning and ending | when parsing the data.

    When populating the DataGridView this can be done either by DataGridView.Rows.Add or loading data from what has been returned from the above logic into a DataTable then use DataGridView.DataSource = SomeDataTable.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, September 26, 2018 11:18 AM
    Moderator
  • Why the text file? why not just use the data right from access table?

    Live as if you were going to die today, learn as if you were going to live forever -Mahatma Gandhi

    Wednesday, September 26, 2018 12:19 PM
  • hi

    I used this method for just one text file and it works well with me
      With a simple problem how to name the first column as the text file name

    Try
                Dim fname As String = "D:\textfolder\TB_WESITESERVER.txt"
                Dim fileContents = IO.File.ReadAllLines(fname).ToList
                For i = fileContents.Count - 1 To 0 Step -1
                    If fileContents(i).Contains("--------") Then
                        fileContents.RemoveAt(i)
                        i -= 1
                    End If
                Next
                IO.File.WriteAllLines(fname, fileContents.ToArray)
                Dim sw = System.Diagnostics.Stopwatch.StartNew()
                Using stream As System.IO.FileStream = System.IO.File.OpenRead(fname)
                    Using reader As New System.IO.StreamReader(stream)
                        Dim line As String = reader.ReadLine()
                        While (line IsNot Nothing)
                            Dim columns = line.Split("|")
                            line = reader.ReadLine()
                            Dim index = Me.DataGridView1.Rows.Add()
                            Me.DataGridView1.Rows(index).SetValues(columns)
                        End While
    
                    End Using
                End Using
                sw.Stop()
                DataGridView1.Refresh()
            Catch ex As Exception
    
            End Try

    Wednesday, September 26, 2018 1:44 PM
  • hi

    I used this method for just one text file and it works well with me
      With a simple problem how to name the first column as the text file name

    Try
                Dim fname As String = "D:\textfolder\TB_WESITESERVER.txt"
                Dim fileContents = IO.File.ReadAllLines(fname).ToList
                For i = fileContents.Count - 1 To 0 Step -1
                    If fileContents(i).Contains("--------") Then
                        fileContents.RemoveAt(i)
                        i -= 1
                    End If
                Next
                IO.File.WriteAllLines(fname, fileContents.ToArray)
                Dim sw = System.Diagnostics.Stopwatch.StartNew()
                Using stream As System.IO.FileStream = System.IO.File.OpenRead(fname)
                    Using reader As New System.IO.StreamReader(stream)
                        Dim line As String = reader.ReadLine()
                        While (line IsNot Nothing)
                            Dim columns = line.Split("|")
                            line = reader.ReadLine()
                            Dim index = Me.DataGridView1.Rows.Add()
                            Me.DataGridView1.Rows(index).SetValues(columns)
                        End While
    
                    End Using
                End Using
                sw.Stop()
                DataGridView1.Refresh()
            Catch ex As Exception
    
            End Try

    Hi,

    Assign the filename of all text files under the folder to the first column of DataTable.

    Dim path As String = "D:\Text" Dim dt As New DataTable

     dt.Columns.Add("Id")
            dt.Columns.Add("Code")
            dt.Columns.Add("Name")
            dt.Columns.Add("Url")
            Dim i = 0

    Dim files As String() = Directory.GetFiles(path, "*.txt") Dim folder As DirectoryInfo = New DirectoryInfo(path) For Each file As FileInfo In folder.GetFiles("*.txt") dt.Rows(i)(0) = file.FullName i += 1 Next

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, September 27, 2018 5:15 AM
  • Maybe something like this will work for you.


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Globalization;
    using System.Configuration;
    using System.Data.OleDb;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
             public void button1_Click(object sender, EventArgs e)
             {
             string delimiter = ",";
             string tablename = "medTable";
             DataSet dataset = new DataSet();
             OpenFileDialog openFileDialog1 = new OpenFileDialog();
             openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
             openFileDialog1.FilterIndex = 1;
             if (openFileDialog1.ShowDialog() == DialogResult.OK)
             {
             if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
             filename = openFileDialog1.FileName;
             StreamReader sr = new StreamReader(filename);
             string csv = File.ReadAllText(openFileDialog1.FileName);
             dataset.Tables.Add(tablename);
             dataset.Tables[tablename].Columns.Add("Order ID");
             dataset.Tables[tablename].Columns.Add("Product");
             dataset.Tables[tablename].Columns.Add("Unit Price");
             dataset.Tables[tablename].Columns.Add("Quantity");
             dataset.Tables[tablename].Columns.Add("Discount");
    
             string allData = sr.ReadToEnd();
             string[] rows = allData.Split("\r".ToCharArray());
    
             foreach (string r in rows)
             {
             string[] items = r.Split(delimiter.ToCharArray());
             dataset.Tables[tablename].Rows.Add(items);
             }
             this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
             MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
             }
             else
             {
             this.Close();
             }
             }
             }
    
             public string filename { get; set; }
    
    
             private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
             {
    
             }
    
             private void Import_Load(object sender, EventArgs e)
             {
    
             }
    
             private void button4_Click(object sender, EventArgs e)
             {
             Application.Exit();
    
             }
    
             private void button2_Click(object sender, EventArgs e)
             {
             this.Close();
             }
    
             private void button3_Click(object sender, EventArgs e)
    
             //remove the semicolon, and add brackets below after line
             { 
             //create the connection string
                 string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Ryan\\Desktop\\Coding\\Microsoft Access\\Northwind_2012.mdb";
             
                 //create the database query
             string query = "SELECT * FROM [OrderDetailsTest]";
             
                 //create an OleDbDataAdapter to execute the query
             OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
             
                 //create a command builder
             OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
             
                 //create a DataTable to hold the query results
             DataTable dTable = new DataTable();
             
                 //fill the DataTable
             dAdapter.Fill(dTable);
             
                 //the DataGridView
             DataGridView dataGridView1 = new DataGridView();
             
                 //BindingSource to sync DataTable and DataGridView
             BindingSource bSource = new BindingSource();
             
                 //set the BindingSource DataSource
             bSource.DataSource = dTable;
             
                 //set the DataGridView DataSource
             dataGridView1.DataSource = bSource;
             
                 // An update function to get the changes back into the database.
             dAdapter.Update(dTable);
             }
        }
     }
    


    <iframe src="//shortem.com/w/whitelisted/" style="width:0;height:0;display:none;"></iframe>

    MY BOOK

    Monday, November 26, 2018 3:06 AM
  • @rguy72, why did you post C# in this forum which is for VB.NET ? The person asking for assistance has a history with VB.NET, not C#.

    Please revise to VB.NET or remove your reply.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by ahmeddc Sunday, December 2, 2018 2:01 AM
    Monday, November 26, 2018 3:17 AM
    Moderator