none
How to read the data from textfile to dataagrid view?

    Question

  • Hi, all master, I need to read the data from textfile to datagridview, but I am fail about this Operator " | ", please suggest me to good solution

    example:

    this data in textfile

    3333;3333;3333|
    6666;6666;6666|

    and I try to demo my fail code, then it is like this picture "|"

     

    thank

    Best regard,

    kevin


    • Edited by Adisone Saturday, March 18, 2017 7:16 AM wrong
    Saturday, March 18, 2017 7:13 AM

All replies

  • Hello,

    To address your question it's not possible to say what you are doing wrong since there is no code. So one way to work through the issue is to read in the data via IO.File.ReadAllLines, accept only lines that are not empty, remove (in memory) the pipe and split. Lastly, this assumes each line has three columns split by a semi-colon.

    Here I placed a file into the same folder as the executable, Bib\Debug folder.

    using System;
    using System.Data;
    using System.Linq;
    using System.Windows.Forms;
    using System.IO;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Doc.txt");
    
                var data = (from line in File.ReadAllLines(fileName)
                            where line.Length > 0
                            // remove | and splut by ;
                            let Items = line.Replace("|", "").Split(';')
                            select new
                            {
                                Col1 = Items[0],
                                Col2 = Items[1],
                                Col3 = Items[2]
                            }).ToList();
    
                foreach (var item in data)
                {
                    dataGridView1.Rows.Add(new object[] { item.Col1, item.Col2, item.Col3 });
                }
    
            }
        }
    }
    
    File content
    3333;3333;3333|
    6666;6666;6666|


    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

    Saturday, March 18, 2017 8:34 AM
    Moderator
  • I need to read the data from textfile to datagridview, but I am fail about this Operator " | ",

    example:

    this data in textfile

    3333;3333;3333|
    6666;6666;6666|

    and I try to demo my fail code, then it is like this picture "|"


    So whats the problem? The last value seems to match what you posted for
    the file data. It has a vertical bar at the end.

    3333;3333;3333|
    6666;6666;6666|

    Describe the problem: What are you expecting to see that you aren't?
    What *aren't you expecting to see that you are?

    Then also show the code being used for that operation.

    - Wayne

    Saturday, March 18, 2017 8:34 AM
  • Sunday, March 19, 2017 3:42 AM
  • You have to create Columns first to dataGrid. Add below lines of code before foreach 

    dataGridView1.ColumnCount = 3;
                dataGridView1.Columns[0].Name = "Column1";
                dataGridView1.Columns[1].Name = "Column2";
                dataGridView1.Columns[2].Name = "Column3";



    PS.Shakeer Hussain


    Sunday, March 19, 2017 4:09 AM
  • Here is a working sample to try out

    https://1drv.ms/u/s!AtGAgKKpqdWjiDCU6rTh1WrILBa2


    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

    Sunday, March 19, 2017 12:35 PM
    Moderator
  • thank you so much for suggest  with best samples
    Sunday, March 19, 2017 12:59 PM
  • My issue is done already, I have to thank "Madam Karen Payne" , and thank you so much for reply
    Sunday, March 19, 2017 2:37 PM
  • Good morning with the nice day, Today I try your code with 10 line, The code is working good, but I try to increase more line (10,000 ), it is working long time.

    Please suggest me more, How to manage this event when read bigger data from text file.

    Sorry for disturb master again.

    Thank you,

    Best regard,

    kevin

    Monday, March 20, 2017 12:33 AM
  • Hello,

    If you had indicated there were 10,000 line I would have indicated a StreamReader e.g.

    using (StreamReader sr = File.OpenText("your file name goes here"))
    {
        string line = String.Empty;
        string[] Items = { } ;
        while ((line = sr.ReadLine()) != null)
        {
            // process the line, remove the | and use split to get colums
            if (!string.IsNullOrWhiteSpace(line))
            {
                Items = line.Replace("|", "").Split(';');
                // use the array elements to populate a row in the DataGridView
            }
                        
        }
    }


    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

    Monday, March 20, 2017 1:03 AM
    Moderator
  • Thank you for your suggest, and Sorry for disturb again !!

    Today I try to add "openFileDialog Control" to your structure code format, but it has issue a bit.

    With this code:

    using (StreamReader  FileStream = new StreamReader(openFileDialog1.FileName))
                        {
                            //dim s() as string = IO.File.ReadAllLines(OpenFileDialog1.FileNAme)
                            var fileName = FileStream.ReadLine();
                            var data = (from line in File.ReadAllLines(fileName) where line.Length > 0
                            // remove | and split by ;
                            let Items = line.Replace("|", "").Split(';') select new
                            {
                                Col1 = Items[0],Col2 = Items[1],Col3 = Items[2],Col4 = Items[3],Col5 = Items[4],Col6 = Items[5],Col7 = Items[6],Col8 = Items[7],
                                Col9 = Items[8],Col10 = Items[9],Col11 = Items[10],Col12 = Items[11],Col13 = Items[12],Col14 = Items[13],Col15 = Items[14],Col16 = Items[15],
                                Col17 = Items[16],Col18 = Items[17],Col19 = Items[18],Col20 = Items[19],Col21 = Items[20],Col22 = Items[21],Col23 = Items[22],Col24 = Items[23],
                                Col25 = Items[24],Col26 = Items[25],Col27 = Items[26],Col28 = Items[27]
    
                            }).ToList();
    
                         foreach (var item in data)
                          {
                          dataGridView1.Rows.Add(new object[] { item.Col1, item.Col2, item.Col3, item.Col4, item.Col5, 
                          item.Col6, item.Col7, item.Col8, item.Col9, item.Col10, item.Col11, item.Col2,item.Col13,
                          item.Col14, item.Col5,item.Col6,item.Col17, item.Col18, item.Col19,item.Col20,item.Col21, 
                          item.Col22, item.Col23,item.Col24,item.Col25, item.Col26, item.Col27,item.Col28 });
                          }
                          this.label1.Text = this.dataGridView1.RowCount.ToString();
                          }

    Please suggest me about error event, please see this


    • Edited by Adisone Monday, March 20, 2017 11:22 AM not good view
    Monday, March 20, 2017 11:20 AM
  • Not sure why you have a variable named fileName where it's used with FileStream.ReadAllLines, seems fileName should be openFielDialog1.FileName. Even with that why are you reading the file with StreamReader then also with FileReadAllLines.

    Please follow the pattern I laid out in my last reply and you will be fine but following the current path will not work.


    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

    Monday, March 20, 2017 11:44 AM
    Moderator
  • Thank you for reply, and Thank for  best suggest the information, Now I try to follow your format, It has a bit issue to happened

    by this code

    const string path = @"d:\texttry.txt"; using (StreamReader sr = File.OpenText(path)) { string line = String.Empty; string[] Items = { }; DataTable dt = new DataTable(); while ((line = sr.ReadLine()) != null) { // process the line, remove the | and use split to get colums if (!string.IsNullOrWhiteSpace(line)) { Items = line.Replace("|", "").Split(';'); // use the array elements to populate a row in the DataGridView

    DataRow dr = dt.NewRow();

    //string[] values = newline.Replace("|", "").Split(';');

    for (int i = 0; i < Items.Length; i++) { dr[i] = Items[i]; } dt.Rows.Add(dr); } dataGridView1.DataSource = dt; } }

    and the issue warning issue is :

    Tuesday, March 21, 2017 2:09 AM
  • What are the errors? I can tell from simply seeing the red X's.

    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

    Tuesday, March 21, 2017 9:37 AM
    Moderator
  • Hi Adisone,

    Please look into below code. You are missing some parameters like you didn't provide the column in datatable in which datarow value will get assign. See the bold lines. Hope this helps you.

    using System;
    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    
    namespace TEXTtoDGV
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {            
                const string path = @"C:\Desktop\Temp Work\TT.txt";
                using (StreamReader sr = File.OpenText(path))
                {
                    string line = String.Empty;
                    string[] Items = { };
    
                    DataTable dt = new DataTable();
                    dt.Columns.Add("SplitValue", typeof(int));
                    DataRow dr;
    
                    while ((line = sr.ReadLine()) != null)
                    {
                        // process the line, remove the | and use split to get colums
                        if (!string.IsNullOrWhiteSpace(line))
                        {
                            Items = line.Replace("|", "").Split(';');
                            // use the array elements to populate a row in the DataGridView
    
                            //DataRow dr = dt.NewRow();
    
                            //string[] values = newline.Replace("|", "").Split(';');
    
                            for (int i = 0; i < Items.Length; i++)
                            {                            
                                dr = dt.NewRow();
                                dr["SplitValue"] = Items[i];
                                dt.Rows.Add(dr);
                            }
                            //dt.Rows.Add(dr);
                        }
                        dataGridView1.DataSource = dt;
                    }
                }
            }
        }
    }

    Output:

    DGV output


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Tuesday, March 21, 2017 11:31 AM
    Moderator
  • Hi Adisone,

    If your issue is solved please Mark as answer or Vote as helpful post to the appropriate answer so that it will help other members to find solution if they faces similar issue.

    Your understanding and cooperation will be grateful.

    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Tuesday, March 21, 2017 2:12 PM
    Moderator
  • Thank you master Sabah Shariq,

    for the final format that solved my issue , I am finished a few hour by the code below:

    this is solution:

    this is code:

     private void button2_Click(object sender, EventArgs e)
            {
    
     
                 try
                  {
                      
                                   
                      dataGridView1.DataSource = User.LoadUserListFromFile(@"C:\17020.txt");
                      this.label1.Text = this.dataGridView1.RowCount.ToString();
                      
     
                    }
    
                    catch (Exception err)
                    {
                        //Display any errors in a Message Box.
                        System.Windows.Forms.MessageBox.Show("Error" + err.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
    
                }
        public class User {
            
    
                public string Qt { get; set; }
                public string ID { get; set; }
                public string BID { get; set; }
                public string Stas { get; set; }
                public string Ltty_1 { get; set; }
                public string Ltty_1 { get; set; }
                public string Ltty_2 { get; set; }
                public string Ltty_2 { get; set; }
                public string Ltty_3 { get; set; }
                public string Ltt_3 { get; set; }
                public string Ltty_4 { get; set; }
                public string Ltty_4 { get; set; }
                public string Ltty_5 { get; set; }
                public string Ltty_5 { get; set; }
                public string Ltty_6 { get; set; }
                public string Ltty_6 { get; set; }
                public string Ltty_7 { get; set; }
                public string Ltty_7 { get; set; }
                public string Lttry_8 { get; set; }
                public string Ltty_8 { get; set; }
                public string Ltty_9 { get; set; }
                public string Ltty_9 { get; set; }
                public string Ltty_10 { get; set; }
                public string Ltty_10 { get; set; }
                public string Ltty_11 { get; set; }
                public string Ltty_11 { get; set; }
                public string Ltty_12 { get; set; }
                public string Ltty_12 { get; set; }
                public static List<User> LoadUserListFromFile(string path) { var users = new List<User>();
    
                   foreach (var line in File.ReadAllLines(path)) { var columns = line.Replace("|", "").Split(';');
                   users.Add(new User {
                   
                       Qt = columns[0],
                       ID = columns[1],
                       BID = columns[2],
                       Stat = columns[3],
                       Ltty_1 = columns[4],
                       Ltty_1 = columns[5],
                       Ltty_2 = columns[6],
                       Ltty_2 = columns[7],
                       Ltty_3 = columns[8],
                       Ltty_3 = columns[9],
                       Ltty_4 = columns[10],
                       Ltty_4 = columns[11],
                       Ltty_5 = columns[12],
                       Ltty_5 = columns[13],
                       Ltty_6 = columns[14],
                       Ltty_6 = columns[15],
                       Ltty_7 = columns[16],
                       Ltty_7 = columns[17],
                       Ltty_8 = columns[18],
                       Ltty_8 = columns[19],
                       Ltty_9 = columns[20],
                       Ltty_9 = columns[21],
                       Ltty_10 = columns[22],
                       Ltty_10 = columns[23],
                       Ltty_11 = columns[24],
                       Ltty_11 = columns[25],
                       Ltty_12 = columns[26],
                       Ltty_12 = columns[27] 
                   });
                   }
    
                   return users;
                  }
    
            //space class
            }

    Lastly, I have to Thank master "Kren Payne" and "Sabah Shariq " that give many solution.

    Best regard,

    Kevin



    • Edited by Adisone Tuesday, March 21, 2017 4:24 PM change
    Tuesday, March 21, 2017 4:13 PM
  • Hi Adisone,

    If your issue is solved please Mark as answer or Vote as helpful post to the appropriate answer so that it will help other members to find solution if they faces similar issue.

    Your understanding and cooperation will be grateful.

    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Tuesday, March 21, 2017 7:33 PM
    Moderator