Features of Datagrid

•Displays data as a table

•Control over

–Alternate item

–Header

–Footer

–Colors, font, borders, etc.

–Paging

•Updateable

•Item as row

Features of Repeater

•List format

•No default output

•More control

•More complexity

•Item as row

•Not updateable

Features of DataList

  • Directional rendering
  • Good for columns
  • Item as cell
  • Alternate item
  • Updateable

Difference between Datagrid and Reapeter Control

Repeator Control:

1)Read-only; no inherent support for selection or editing ·

2)No inherent look; you lay out the list by creating templates.

3)List can be vertical, horizontal, all on one line, or in any format you specify. ·

4)No default paging; all data is displayed in a single list. ·

5)Separators between elements can be defined using a template

Datagrid:

1)Default look is a grid (customizable table) ·

2)Can customize look of table extensively. ·

3)Options for auto-formatting. ·

4)Can specify output using bound columns, columns of buttons or hyperlinks, and custom

columns created using templates. ·

5)No separator template. However, the grid renders in a table, and you can specify table border size and color. ·

6)WYSIWYG template editing ·

7)Items support styles for custom look. ·

8)Editable contents, including deletion ·

9)Single and multiple selection ·

10)Optional paged output ·Support for sorting ·

11)Support for custom functionality that can be applied to items

Datagrid built in paging support

One disadvantage of using the DataGrid control's built-in paging support is performance. When you use the method of paging through records discussed in the preceding section, all the records must be retrieved from the data source every time you navigate to a new page. So, if you are paging through a database table with 2 million records, those 2 million records must be retrieved into memory every time you move to a new page.

 

1) AllowPaging Property to true.

2) PageSize to number of records display per page. Eg: 10.

3) Write Code on Event.

private void DGridEmp_PageIndexChanged(object source,

System.Web.UI.WebControls.DataGridPageChangedEventArgs e)

{

DGridEmp.CurrentPageIndex = e.NewPageIndex;

BindGrid(fetchData());

}

Datagrid Custom Paging

The advantage of this approach to paging through records is that the only records retrieved from the database are the records displayed in the DataGrid. In other words, this approach works great with huge database tables.

Note: This approach works only with database tables that have a column that uniquely indexes each database row. For example, it works with a table that has an identity column when the identity column is not missing any values. If certain values are missing from the identity column, the DataGrid displays fewer records for some pages than others.

1) AllowCustomPaging Property to true.

2) AllowPaging Property to true.

3) PageSize to number of records display per page. Eg: 10.

4) Declare Static Variable

static int iStartIndex;

5) Write Code on Event.

private void Page_Load(object sender, System.EventArgs e)

{

if(!Page.IsPostBack)

{

//Setting DataGrid's Virtual Item count

String connStr,sql;

connStr = ConfigurationSettings.AppSettings

["connStr"];

OleDbConnection conn = new OleDbConnection(connStr);

sql = "select count(*) from emp";

OleDbCommand cmd = new OleDbCommand(sql,conn);

                  conn.open();

DGridEmp.VirtualItemCount =

((int)cmd.ExecuteScalar()/DGridEmp.PageSize);

conn.Close();

iStartIndex = 1;

BindGrid(fetchData(iStartIndex));

}

}

private DataTable fetchData(int iStart)

{

int iEnd = iStart + DGridEmp.PageSize;

String connStr,sql;

connStr = ConfigurationSettings.AppSettings

["connStr"];

OleDbConnection conn = new OleDbConnection(connStr);

sql = "select empid,empname,dob,salary from emp where

empid > " + iStart + " and empid <= " + iEnd + "

order by empid";

                  

DataSet ds = new DataSet();

conn.Open();

OleDbDataAdapter da = new OleDbDataAdapter(sql,conn);

da.Fill(ds,"Emp");

return ds.Tables["Emp"];

}

private void DGridEmp_PageIndexChanged(object source,

System.Web.UI.WebControls.DataGridPageChangedEventArgs e)

{

iStartIndex = (e.NewPageIndex * DGridEmp.PageSize);

DGridEmp.CurrentPageIndex = e.NewPageIndex;

BindGrid(fetchData(iStartIndex));

}

Datagrid Sorting

1) AllowSorting Property to true.

2) Set the SortExpression Property of individual column to their respective field name. Eg: EmpId, EmpName, etc.

3) Write Code on Event.

private void Page_Load(object sender, System.EventArgs e)

{

if(!Page.IsPostBack)

{

BindGrid(fetchData());

ViewState["SortOrder"] = "ASC";

}

}

private void DataGrid1_SortCommand(object source,

System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

{

DataView dv = new DataView(fetchData());

dv.Sort = e.SortExpression + " " + ViewState["SortOrder"];

BindGrid(dv);

if(ViewState["SortOrder"].ToString().ToUpper() == "ASC")

ViewState["SortOrder"] = "DESC";

else

ViewState["SortOrder"] = "ASC";

}

Image Displaying in Datagrid

private void DataGrid1_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e)

{

string sEmpImgPath = String.Empty;

if(e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

{

//For Displaying Image

//-->Start

System.Web.UI.WebControls.Image ImgPhoto =

(System.Web.UI.WebControls.Image)

e.Item.Cells[4].FindControl("ImgPhoto");

//Cell which is mark visible false and contain

//Image path.

sEmpImgPath = e.Item.Cells[5].Text;

if(ImgPhoto != null)

{

if(sEmpImgPath.Length != 0 &&

sEmpImgPath != " ") //Emp Pic Avaliable

{

ImgPhoto.ImageUrl = sEmpImgPath;

}

else

{

ImgPhoto.ImageUrl =

"EmpPic\\default.gif";

}

}

//-->End

}

}

Email Link for Name Field in Datagrid

  • Two fields are to be combined into one. ie: Email field and Name field should be displayed as Name field with Hyperlink to its email
  • To perform this task we need to create email field as invisible field.
  • And we need to convert Name field to template field which consist of two controls Label which is invisible and a hyperlink control.

private void DataGrid1_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e)

{

HyperLink hlk = new HyperLink();

Label lblName = new Label();

Label lblEmail = new Label();

if(e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

{

hlk =(HyperLink) e.Item.Cells[1].FindControl("HyperLink1");

if(hlk != null)

{

lblName =(Label) e.Item.Cells[1].FindControl("lblName");

lblEmail =(Label)

e.Item.Cells[2].FindControl("lblEmail");

if(lblName != null )

{

hlk.Text = lblName.Text;

if(lblEmail != null)

hlk.NavigateUrl = "mailto:" + lblEmail.Text;

else

hlk.NavigateUrl = "mailto: noemail@email.com";

}

}

}

Export Datagrid Data To Excel

private void btnExportToExcel_Click(object sender,
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}


private void ExportToExcel(string strFileName,DataGrid dg)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Export Datagrid Data To MS-Word

private void btnExportToWord_Click(object sender,
System.EventArgs e)
{
ExportToWord("Report.doc",DataGrid1);
}


private void ExportToWord(string strFileName,DataGrid dg)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-word";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Import Excel To Datagrid

Note: If you want to give client upload facility, than first upload the file to the server. Next call the excel file from the following server location.

private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";

DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);

//da.TableMappings.Add("Table", "ExcelTest");

da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}

Master\Child for Datagrid

Declare global variable

DataSet ds = new DataSet();
double dTotalSalary=0;

private void dgMaster_SelectedIndexChanged(object sender,
System.EventArgs e)
{
int iDeptId;
iDeptId = Convert.ToInt32(
dgMaster.DataKeys[dgMaster.SelectedIndex]);
DataView dv = new DataView(fetchChildData());
dv.RowFilter = "DeptId = " + iDeptId;
BindChild(dv);
}

private void dgChild_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item
e.Item.ItemType == ListItemType.AlternatingItem)
{
dTotalSalary +=
Convert.ToDouble(e.Item.Cells[2].Text);
}
else if(e.Item.ItemType == ListItemType.Footer)
{
e.Item.Cells[0].ColumnSpan =3;
e.Item.Cells[0].HorizontalAlign =
HorizontalAlign.Center;

e.Item.Cells.RemoveAt(2);
e.Item.Cells.RemoveAt(1);

e.Item.Cells[0].Text = "Total Salary: " +
dTotalSalary.ToString("C");
}
}

Most Recent Post

Most Recent Ado.net FAQ

Most Recent .Net Framework FAQ

Most Recent Configuration Files FAQ

Daily Quote, Motivation, Inspiration and More

Subscribe Blog via Email

Enter your email address: