Possible Duplicate:
Putting a .txt file into a DataGridView
When I click an open button I would like to choose a file and place it into a DataSource to futher be worked into a DataGridView.
Right now what I have looks like this:
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = "*.txt";
openFile.Filter = ".txt Files|*.txt";
openFile.RestoreDirectory = true;
try
{
if (openFile.ShowDialog() == DialogResult.OK && openFile.FileName.Length > 0)
{
// Right now I am loading the file into a RichTextBox
openFileRTB.LoadFile(openFile.FileName, RichTextBoxStreamType.PlainText);
// What I would like to do is load it into a DataSource and then into a DataGridView.
// So really I would like to remove the openFileRTB line of code and replace it.
// That is where I need help :).
}
}
catch (Exception)
{
MessageBox.Show("There was not a specified file path to open.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
Here is an example of a file I would be opening (space delimited):
Title1 Title2 Title3 Title4 Title5 Title6
abc123 abc123-123-123 225.123 123.456 180 thing99
c123 somethingHERE 987.123 123.456 360 anotherThing1
abc124 somethingHERE225.123 123.456 0 thing99
I am very unfamiliar with DataSource and DataGridView so if I could get some help with how it works and what needs to happen, how it would look, etc. that would be greatly appreciated. 🙂
Thanks.
You could split the lines and loop all rows/columns to generate the DataTable:
For example(VB.NET):
This works just as well without LINQ (now also in C# ;)):