Showing posts with label Read Text File and Display in Grid View. Show all posts
Showing posts with label Read Text File and Display in Grid View. Show all posts

Wednesday, August 12, 2009

Read Text File and Display in Grid View

protected void Page_Load
(object sender, EventArgs e)
{
if (!IsPostBack)
{
string openpath, contents;
int tabsize = 4;
string[] arinfo;
string line;
int i;
DataTable dt = CreateTable();
DataRow row;
try
{
openpath =
Server.MapPath(".") + @"\abhi.txt";
string filename = openpath;
StreamReader st;
st = File.OpenText(filename);
while ((line = st.ReadLine()) != null)
{
contents =
line.Replace(("").PadRight(tabsize, ' '), "\t");
char[] textdelimeter = { ']' };
arinfo = contents.Split(textdelimeter);
for (i = 0; i < arinfo.Length; i++)
{
row = dt.NewRow();
if (i < arinfo.Length)
row["name"] = arinfo[i].ToString().Replace("[", "");
if (i < arinfo.Length)
row["lastname"] = arinfo[i].ToString().Replace("[", "");
dt.Rows.Add(row);
}
i++;

}
st.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}


}


}


private DataTable CreateTable()
{
try
{
DataTable table = new DataTable();

// Declare DataColumn and DataRow variables.
DataColumn column;

// Create new DataColumn, set DataType, ColumnName
// and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "name";
table.Columns.Add(column);

// Create second column.
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "lastname";
table.Columns.Add(column);


return table;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}