The following snippet is used to load data from text file to grid view.
Step 1:
suppose u have text file(Employee.text) with following data
empid,empname
101,ganesh
102,manu
103,chandra
104,joseph
105,rutherford
Step 2:
Retreving the above text data and assigning to gridview
//streamreader object is created for the text file
StreamReader sr = new StreamReader(@"c:\employee.txt");
//dataset object is created
DataSet ds = new DataSet();
ds.Tables.Add("emp");
//reading the first line in text file which is columnheader
string colheader = sr.ReadLine();
//splitting the line excluding,
string[] cols = System.Text.RegularExpressions.Regex.Split(colheader, ",");
//adding columns to gridview
for (int c = 0; c < cols.Length; c++)
ds.Tables[0].Columns.Add(cols[c]);
//reading the next lines in text file which constitutes rows
string row = sr.ReadLine();
//spliting each line till the end of text and assigning to gridview
while (row != null)
{
string[] rvalues = System.Text.RegularExpressions.Regex.Split(row, ",");
ds.Tables[0].Rows.Add(rvalues);
row = sr.ReadLine();
}
dataGridView1.DataSource = ds.Tables[0];
Explanation:
The text file consists of some important data which is separated by commas. The above snippet is designed to derive the data in the format which is suitable for displaying in grid view.