Features of Datagrid
•Displays data as a table
•Control over
–Alternate item
–Header
–Footer
–Colors, font, borders, etc.
–Paging
•Updateable
•Item as row
Datagrid, Repeater and DataList Control explanation and programming example. Easy Examples for Datagrid Programming in asp.net.
For .Net Articles, Links, Code and much more logon to DailyFreeCode.com
•Displays data as a table
•Control over
–Alternate item
–Header
–Footer
–Colors, font, borders, etc.
–Paging
•Updateable
•Item as row
www.DailyFreeCode.com --- DotNetGuts 0 comments
•List format
•No default output
•More control
•More complexity
•Item as row
•Not updateable
www.DailyFreeCode.com --- DotNetGuts 0 comments
www.DailyFreeCode.com --- DotNetGuts 0 comments
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
www.DailyFreeCode.com --- DotNetGuts 1 comments
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());
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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));
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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";
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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
}
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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";
}
}
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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();
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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();
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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();
}
www.DailyFreeCode.com --- DotNetGuts 0 comments
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");
}
}
www.DailyFreeCode.com --- DotNetGuts 0 comments