Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to know if it is possible to read lines from a Text File and then inserting those values into a Data Grid View in my Program.

I am currently only able to save to a text file, but cannot read from the same file.

If any one would be so kind as to assist me
Posted
Comments
Tarun.K.S 15-Jul-11 9:05am    
Use the StreamReader and use its ReadLine() method to read lines.

1 solution

Well, it would help to know exactly what you want but Ill give you a basic example.

public class MyDataObject
{
public string FirstName {get; set; }
public string LastName {get; set; }
}


We will use the above object. Then in your Program.cs (or where ever you want to execute your code)

using (System.IO.StreamReader sr = new System.IO.StreamReader("MyFileName"))
{
List<mydataobject> myList = new List<mydataobject>();
//Do your own reading in logic here, I will do a basic example assuming that
//the first and last names are comma separated, and each entry is on a new line
string[] names = sr.ReadToEnd().split('\n');
foreach (string s in names)
{
string[] values = s.split(',');
myList.Add(new MyDataObject { FirstName = values[0], LastName = values[1] });
}
//Now set your data grid's datasource to myList and call the DataBind() method and you are good to go!
}

That is the most basic way I can think of doing it?
 
Share this answer
 
v3
Comments
DominicZA 15-Jul-11 9:14am    
Dont worry about those last two tags!! They keep adding themselves!
Tarun.K.S 15-Jul-11 9:17am    
Damn you are right! :D
thatraja 15-Jul-11 12:25pm    
No he is not :)
thatraja 15-Jul-11 12:25pm    
/*Dont worry about those last two tags!! They keep adding themselves!*/
No, I changed that. See there :)
DominicZA 15-Jul-11 9:29am    
haha!! Glad I could help! Could you please mar as answered ;) Thanks..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900