// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// The Common Usage For GridView (Version 7.0)
// Author: Behrouz Rad
// Copyright © 2006 - 2009, All rights reserved.
// feel free to contact me: behrouz.rad@gmail.com
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BehooGridViewFunctions;
using BehooGridViewFunctions.BLL.Orders;
using BehooGridViewFunctions.Helpers;
public partial class _Default : BasePage, ICallbackEventHandler
{
public void BindGridView(int gvPageIndex, int gvPageSize)
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
try
{
List<Order> orders = Order.GetOrders(gvPageIndex, gvPageSize);
int totRecords = Order.GetTotalOrders;
SiteHelper.Fill_Paging_DropDown(totRecords, orderPageSize, drpPaging, litTotalRecords, litCurrentPageState);
if (this.IsPostBack && ViewState["drpPagingIndex"] != null)
{
drpPaging.SelectedIndex = (int)(ViewState["drpPagingIndex"]);
}
GridView1.DataSource = orders;
GridView1.DataBind();
}
catch (ArgumentOutOfRangeException)
{
int pi = (int)ViewState["drpPagingIndex"];
pi = pi - 1;
ViewState["drpPagingIndex"] = pi;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
if (!this.IsPostBack)
{
this.BindGridView(0, orderPageSize);
}
string callback = this.ClientScript.GetCallbackEventReference(this, "myValue", "ReceiveDataFromServer", "validateF");
if (!this.ClientScript.IsClientScriptBlockRegistered("DoServerAction"))
{
string script = "function DoServerAction(myValue,validateF) {" + callback + "}";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoServerAction", script, true);
}
}
protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList xList = (DropDownList)sender;
TableCell cell = (TableCell)xList.Parent;
GridViewRow item = (GridViewRow)cell.Parent;
DropDownList modelList = null;
if (item.RowType == DataControlRowType.EmptyDataRow)
{
modelList = (DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_ModelDropDown");
}
else
{
modelList = (DropDownList)item.Cells[3].Controls[1];
}
try
{
int parentId = Int32.Parse(xList.SelectedValue, CultureInfo.InvariantCulture);
List<ChildPiece> childPieces = ChildPiece.GetChildPieces(parentId);
modelList.DataSource = childPieces;
modelList.DataTextField = "SubPieceName";
modelList.DataValueField = "SubPieceName";
modelList.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
string[] arrValues = null;
string sidValues = Session["sid_values"] as string;
if (sidValues != null)
{
arrValues = sidValues.Split(',');
ListItem xChildItem = modelList.Items.FindByText(arrValues[2]);
if (xChildItem != null)
{
xChildItem.Selected = true;
}
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
GridView1.ShowFooter = true;
GridView1.EditIndex = -1;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
protected void DoInsert(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert" || e.CommandName == "EmptyInsert")
{
string organName = string.Empty;
string pieceName = string.Empty;
string subPieceName = string.Empty;
string orderId = string.Empty;
if (e.CommandName == "Insert")
{
GridViewRow rowFooter = GridView1.FooterRow;
organName = ((DropDownList)rowFooter.FindControl("Add_OrganDropDown")).SelectedItem.Text;
pieceName = ((DropDownList)rowFooter.FindControl("Add_PieceDropDown")).SelectedItem.Text;
subPieceName = ((DropDownList)rowFooter.FindControl("Add_ModelDropDown")).SelectedItem.Text;
orderId = ((TextBox)rowFooter.FindControl("Add_OrderID")).Text;
}
else if (e.CommandName == "EmptyInsert")
{
organName = ((DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_OrganDropDown")).SelectedItem.Text;
pieceName = ((DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_PieceDropDown")).SelectedItem.Text;
subPieceName = ((DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_ModelDropDown")).SelectedItem.Text;
orderId = ((TextBox)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_OrderID")).Text;
}
orderId = string.IsNullOrEmpty(orderId) ? "0" : orderId;
try
{
bool isInserted = Order.InsertOrder(organName, pieceName, subPieceName, Int32.Parse(orderId, CultureInfo.InvariantCulture));
if (!isInserted)
{
Response.Write(@"<b>Error in Adding!</b>");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
string rowID = string.Empty;
if (e.Row.RowType == DataControlRowType.Header)
{
for (int counter = 0; counter <= 6; counter++)
{
TableCell cellSpan = (TableCell)e.Row.Cells[counter];
cellSpan.RowSpan = 2;
}
LiteralControl litColumn = new LiteralControl();
litColumn.Text = "حذف";
e.Row.Cells[7].Controls.Add(litColumn);
GridViewRow xItem = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableCell xCell = new TableCell();
HtmlInputButton btnSel = new HtmlInputButton();
btnSel.ID = "btnSelectDeselect";
btnSel.Attributes.Add("Style", "background-color:#FFC080;border-width:1px;border-style:Solid;Font-Family:Tahoma; Font-Size:11px");
btnSel.Attributes.Add("onclick", "this.value=select_deselectAll();");
btnSel.Value = "انتخاب همه";
xCell.Controls.Add(btnSel);
xCell.Attributes.Add("align", "center");
xCell.BackColor = Color.FromArgb(Int32.Parse("5A49A7", NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture));
xItem.Controls.Add(xCell);
e.Row.Cells[7].Controls.Add(xItem);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
Literal ref_LitRowNumberNormal = (Literal)e.Row.FindControl("litRowNumberNormal");
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
ref_LitRowNumberNormal.Text = ViewState["drpPagingIndex"] != null ? SiteHelper.GridViewRowsIndexing((int)ViewState["drpPagingIndex"], orderPageSize, e.Row.RowIndex) : SiteHelper.GridViewRowsIndexing(0, orderPageSize, e.Row.RowIndex);
rowID = "row" + e.Row.RowIndex.ToString(CultureInfo.InvariantCulture);
e.Row.Attributes.Add("id", rowID);
e.Row.Attributes.Add("onmouseover", "rowOver(" + "'" + rowID + "'" + ")");
e.Row.Attributes.Add("onmouseout", "rowOut(" + "'" + rowID + "'" + ")");
e.Row.Attributes.Add("class", "contextEntry");
CheckBox chkDel = (CheckBox)e.Row.Cells[7].Controls[1];
chkDel.Attributes.Add("onclick", "rowAppearanceOnDeleteMode(" + "'" + rowID + "'" + ")");
Button editButton = (Button)e.Row.Cells[6].Controls[0];
editButton.BackColor = Color.FromKnownColor(KnownColor.LightCoral);
editButton.BorderWidth = Unit.Pixel(1);
editButton.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px");
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
Literal ref_LitRowNumberFooter = (Literal)e.Row.FindControl("litRowNumberFooter");
try
{
int totOrders = Order.GetTotalOrders + 1;
ref_LitRowNumberFooter.Text = totOrders.ToString(CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Button btnRemove = (Button)e.Row.Cells[7].Controls[1];
btnRemove.OnClientClick = "return confirmDelete();";
Button btnAdd = new Button();
btnAdd.ID = "btnAdd";
btnAdd.Text = "اضافه";
btnAdd.CommandName = "Insert";
btnAdd.BorderStyle = BorderStyle.Solid;
btnAdd.BorderWidth = new Unit(1, UnitType.Pixel);
btnAdd.BackColor = Color.FromArgb(Int32.Parse("FFC080", System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture));
btnAdd.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px");
e.Row.Cells[6].Controls.Add(btnAdd);
}
else if (e.Row.RowType == DataControlRowType.Pager)
{
LiteralControl litGoToText = new LiteralControl();
litGoToText.Text = @"<span dir=""rtl"">برو به صفحه </span>";
e.Row.Cells[0].Controls.Add(litGoToText);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList drpOrganList = null;
DropDownList drpPieceList = null;
if ((e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit) || (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState.ToString() == "Alternate, Edit"))
{
Button updateButton = (Button)e.Row.Cells[6].Controls[0];
updateButton.BackColor = Color.FromKnownColor(KnownColor.Green);
updateButton.BorderWidth = Unit.Pixel(1);
updateButton.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px");
Button cancelButton = (Button)e.Row.Cells[6].Controls[2];
cancelButton.BackColor = Color.FromKnownColor(KnownColor.LightCoral);
cancelButton.BorderWidth = Unit.Pixel(1);
cancelButton.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px");
drpOrganList = (DropDownList)e.Row.Cells[1].FindControl("OrganDropDown");
drpPieceList = (DropDownList)e.Row.Cells[2].FindControl("PieceDropDown");
try
{
List<Organ> organs = Organ.GetOrgans();
drpOrganList.DataSource = organs;
drpOrganList.DataTextField = "OrganName";
drpOrganList.DataValueField = "ID";
drpOrganList.DataBind();
List<ParentPiece> parentPieces = ParentPiece.GetParentPieces();
drpPieceList.DataSource = parentPieces;
drpPieceList.DataTextField = "PieceName";
drpPieceList.DataValueField = "ID";
drpPieceList.DataBind();
string[] arrValues = ((string)Session["sid_values"]).Split(',');
ListItem xOrganItem = drpOrganList.Items.FindByText(arrValues[0]);
ListItem xParentItem = drpPieceList.Items.FindByText(arrValues[1].ToString());
if (xOrganItem != null)
{
xOrganItem.Selected = true;
}
if (xParentItem != null)
{
xParentItem.Selected = true;
}
this.DropDown_SelectedIndexChanged(drpPieceList, e);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
else if (e.Row.RowType == DataControlRowType.Footer || e.Row.RowType == DataControlRowType.EmptyDataRow)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
drpOrganList = (DropDownList)e.Row.Cells[1].FindControl("Add_OrganDropDown");
drpPieceList = (DropDownList)e.Row.Cells[2].FindControl("Add_PieceDropDown");
}
else if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
drpOrganList = (DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_OrganDropDown");
drpPieceList = (DropDownList)GridView1.Controls[0].Controls[0].FindControl("Add_Empty_PieceDropDown");
}
try
{
List<Organ> organs = Organ.GetOrgans();
drpOrganList.DataSource = organs;
drpOrganList.DataTextField = "OrganName";
drpOrganList.DataValueField = "ID";
drpOrganList.DataBind();
List<ParentPiece> parentPieces = ParentPiece.GetParentPieces();
drpPieceList.DataSource = parentPieces;
drpPieceList.DataTextField = "PieceName";
drpPieceList.DataValueField = "ID";
drpPieceList.DataBind();
this.DropDown_SelectedIndexChanged(drpPieceList, e);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
CheckBox chkRemove;
string ids = string.Empty;
bool isChecked = false;
foreach (GridViewRow gvRow in GridView1.Rows)
{
chkRemove = (CheckBox)gvRow.FindControl("ChkRemove");
if (chkRemove.Checked)
{
isChecked = true;
ids += GridView1.DataKeys[gvRow.RowIndex].Value + ",";
}
}
if (isChecked)
{
try
{
Order.DeleteOrder(ids, ',');
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.ShowFooter = false;
string organ = string.Empty;
string parentPiece = string.Empty;
string childPiece = string.Empty;
organ = ((DataBoundLiteralControl)GridView1.Rows[e.NewEditIndex].Cells[1].Controls[0]).Text.Trim();
parentPiece = ((DataBoundLiteralControl)GridView1.Rows[e.NewEditIndex].Cells[2].Controls[0]).Text.Trim();
parentPiece = Regex.Replace(parentPiece, @"\s*<div(.*|\s*){1,}</div>\s*", string.Empty);
childPiece = ((DataBoundLiteralControl)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Text.Trim();
Session["sid_values"] = string.Concat(organ, ",", parentPiece, ",", childPiece);
GridView1.EditIndex = e.NewEditIndex;
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string organName = string.Empty;
string pieceName = string.Empty;
string subPieceName = string.Empty;
string orderId = string.Empty;
int rowId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value, CultureInfo.InvariantCulture);
GridViewRow rowEdit = GridView1.Rows[e.RowIndex];
organName = ((DropDownList)rowEdit.FindControl("OrganDropDown")).SelectedItem.Text;
pieceName = ((DropDownList)rowEdit.FindControl("PieceDropDown")).SelectedItem.Text;
subPieceName = ((DropDownList)rowEdit.FindControl("ModelDropDown")).SelectedItem.Text;
orderId = ((TextBox)rowEdit.FindControl("OrderID")).Text;
orderId = string.IsNullOrEmpty(orderId) ? "0" : orderId;
try
{
Order.UpdateOrder(rowId, organName, pieceName, subPieceName, Int32.Parse(orderId, CultureInfo.InvariantCulture));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
GridView1.ShowFooter = true;
GridView1.EditIndex = -1;
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
this.BindGridView(ViewState["drpPagingIndex"] != null ? (int)ViewState["drpPagingIndex"] : 0, orderPageSize);
}
}
protected override void OnLoadComplete(EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox ref_chk = (CheckBox)gvRow.FindControl("chkRemove");
this.ClientScript.RegisterArrayDeclaration("chk_Array_IDs", string.Concat("'", ref_chk.ClientID, "'"));
}
if (GridView1.Rows.Count > 0)
{
gridelement.Value = GridView1.FooterRow.Cells[7].Controls[1].ClientID + "," + GridView1.FooterRow.Cells[6].Controls[0].ClientID + "," + GridView1.HeaderRow.Cells[7].Controls[1].Controls[0].Controls[0].ClientID;
}
base.OnLoadComplete(e);
}
public override void VerifyRenderingInServerForm(Control control)
{
// DON'T REMOVE THIS METHOD!!!
// >>> This means that we are overriding the default implementation of the
// method and giving permission to the GridView to be exported as
// an Excel file.
}
protected enum ExportType
{
ExportToExcel,
ExportToWord,
ExportToText
}
protected void ExportData(ExportType exportType, int fromIndex, int toIndex)
{
try
{
List<Order> orders = Order.GetOrdersInRange(fromIndex, toIndex);
int numRows = orders.Count;
string fileToExport = string.Empty;
string contentType = string.Empty;
StringBuilder sb = new StringBuilder();
switch (exportType)
{
case ExportType.ExportToExcel:
sb.Append(@"<html><head><meta http-equiv=Content-Type content=""text/html; charset=utf-8""><style> .text { mso-number-format:\@; } .trFormat{color:Black;background-color:#DEDFDE;} </style></head><table dir=""rtl"" cellspacing=""1"" cellpadding=""3"" border=""0"" style=""background-color:White;border-color:White;border-width:2px;border-style:Ridge;font-family:Tahoma;font-size:11px;width:100%;""><tbody>");
sb.Append(@"<tr style=""color:#E7E7FF;background-color:#4A3C8C;font-weight:bold;"">");
sb.Append(@"<th>نام اداره</th><th>نام قطعه</th><th>مدل قطعه</th><th>شماره تقاضا</th></tr>");
for (int rowCounter = 0; rowCounter < numRows; rowCounter++)
{
sb.Append(string.Concat(@"<tr class=""trFormat""><td>",
orders.ElementAt(rowCounter).OrganName,
@"</td><td>",
orders.ElementAt(rowCounter).PieceName,
@"</td><td align=""center"">",
orders.ElementAt(rowCounter).SubPieceName,
@"</td><td align=""center"">",
orders.ElementAt(rowCounter).PieceID,
@"</tr>"));
}
sb.Append(@"</tbody></table></html>");
sb.Replace(@"ی", @"ی");
fileToExport = @"GridView_ExcelFormat.xls";
contentType = @"application/vnd.xls;";
break;
case ExportType.ExportToWord:
sb.Append(@"<html><head><meta http-equiv=Content-Type content=""text/html; charset=utf-8""><style> .trFormat{color:Black;background-color:#DEDFDE;} </style></head><table dir=""rtl"" cellspacing=""1"" cellpadding=""3"" border=""0"" style=""background-color:White;border-color:White;border-width:2px;border-style:Ridge;font-family:Tahoma;font-size:11px;width:100%;""><tbody>");
sb.Append(@"<tr style=""color:#E7E7FF;background-color:#4A3C8C;font-weight:bold;"">");
sb.Append(@"<th>نام اداره</th><th>نام قطعه</th><th>مدل قطعه</th><th>شماره تقاضا</th></tr>");
for (int rowCounter = 0; rowCounter < numRows; rowCounter++)
{
sb.Append(string.Concat(@"<tr class=""trFormat""><td>",
orders.ElementAt(rowCounter).OrganName,
@"</td><td>",
orders.ElementAt(rowCounter).PieceName,
@"</td><td align=""center"">",
orders.ElementAt(rowCounter).SubPieceName,
@"</td><td align=""center"">",
orders.ElementAt(rowCounter).PieceID,
@"</tr>"));
}
sb.Append(@"</tbody></table></html>");
sb.Replace(@"ی", @"ی");
fileToExport = @"GridView_WordFormat.doc";
contentType = @"application/vnd.word;";
break;
case ExportType.ExportToText:
for (int rowCounter = 0; rowCounter < numRows; rowCounter++)
{
sb.AppendLine(string.Concat(orders.ElementAt(rowCounter).OrganName,
" | ",
orders.ElementAt(rowCounter).PieceName,
" | ",
orders.ElementAt(rowCounter).SubPieceName,
" | ",
orders.ElementAt(rowCounter).PieceID));
sb.AppendLine("---------------------------------------------------");
}
fileToExport = @"GridView_TextFormat.txt";
contentType = @"application/vnd.text;";
break;
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + fileToExport);
Encoding encode = Encoding.UTF8;
Response.ContentEncoding = encode;
Response.ContentType = contentType;
Response.Write(sb.ToString());
Response.End();
// Don't Show Error with Response.Write!
// otherwise Error comes in file!
// log it in another way.
}
catch (Exception ex)
{
// Response.Write(ex.Message);
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
this.ExportData(ExportType.ExportToExcel, 1, 10);
}
protected void btnExportToWord_Click(object sender, EventArgs e)
{
this.ExportData(ExportType.ExportToWord, 1, 10);
}
protected void btnExportToText_Click(object sender, EventArgs e)
{
this.ExportData(ExportType.ExportToText, 1, 10);
}
protected void drpPaging_SelectedIndexChanged(object sender, EventArgs e)
{
int orderPageSize = SiteHelper.Settings.Orders.PageSize;
ViewState["drpPagingIndex"] = drpPaging.SelectedIndex;
this.BindGridView(drpPaging.SelectedIndex, orderPageSize);
}
#region ICallbackEventHandler Members
private string strReturn = string.Empty;
private string strFetchResult = string.Empty;
string ICallbackEventHandler.GetCallbackResult()
{
return this.strFetchResult;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
if (!string.IsNullOrEmpty(eventArgument))
{
this.strReturn = eventArgument;
this.strFetchResult = Order.GetOrderByID_Ajax_Format(Int32.Parse(strReturn, CultureInfo.InvariantCulture));
}
}
#endregion
}