Print this page
Monday, 17 June 2013 13:56

how to populate a gridview with DataTable

Written by 
Rate this item
(1 Vote)

following way a DataTable with data can be used to
populate gridview control in asp.net.following codes get files list
from a file path and adds in DataTable then sets that
DataTable as a DataSource of the GridView grdDirList.

protected void Page_Load(object sender, EventArgs e)
{
DataRow drow;
DataTable dt = SetDataTable();

DirectoryInfo dir = new DirectoryInfo(filepath);

FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
drow = dt.NewRow();
drow["FILENAME"] = file.Name;
drow["FILEPATH"] = file.FullName;
drow["FILESIZE"] = GetSizeInMB(file.Length) + " MB";
dt.Rows.Add(drow);
}

if (dt.Rows.Count > 0)
{
grdDirList.DataSource = dt;
grdDirList.DataBind();
} }

private DataTable SetDataTable()
{
DataTable dt = new DataTable();
try
{
DataColumn dcol = new DataColumn("FILENAME", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("FILEPATH", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("FILESIZE", typeof(System.String));
dt.Columns.Add(dcol);

}catch{} return dt;
}

Hope it helps....

Read 3167 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.
7