Answered by:
How to read the data from textfile to dataagrid view?

-
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
Question
Answers
-
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
- Marked as answer by Adisone Saturday, April 29, 2017 12:24 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
- Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 20, 2017 6:33 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:25 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
- Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 20, 2017 6:33 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:25 AM
-
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:
Thanks,
Sabah Shariq[If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click
"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]
- Edited by Sabah ShariqMVP, Moderator Tuesday, March 21, 2017 11:32 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:26 AM
-
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:\170.txt"); } 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 Ltty_1 { get; set; } public string Ltty_2 { get; set; } public string Ltty_3 { get; set; } public string Ltty_4 { 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 { Ltty_1 = columns[0], Ltty_2 = columns[1], Ltty_3 = columns[2], Ltty_4 = columns[3], }); } return users; } //space class }
Lastly, I have to Thank master "Kren Payne" and "Sabah Shariq " that give many solution.
Best regard,
Kevin
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
- Marked as answer by Adisone Saturday, April 29, 2017 12:24 AM
-
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
-
-
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
- Edited by Syed Shakeer HussainMicrosoft contingent staff 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
- Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 20, 2017 6:33 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:25 AM
-
-
-
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
-
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
- Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 20, 2017 6:33 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:25 AM
-
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
-
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
-
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 :
-
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
-
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:
Thanks,
Sabah Shariq[If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click
"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]
- Edited by Sabah ShariqMVP, Moderator Tuesday, March 21, 2017 11:32 AM
- Marked as answer by Adisone Saturday, April 29, 2017 12:26 AM
-
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
"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]
-
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:\170.txt"); } 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 Ltty_1 { get; set; } public string Ltty_2 { get; set; } public string Ltty_3 { get; set; } public string Ltty_4 { 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 { Ltty_1 = columns[0], Ltty_2 = columns[1], Ltty_3 = columns[2], Ltty_4 = columns[3], }); } return users; } //space class }
Lastly, I have to Thank master "Kren Payne" and "Sabah Shariq " that give many solution.
Best regard,
Kevin
-
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
"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]