ASP.net 自定义控件GridView
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.Design;
using System.ComponentModel;
using SILK2010;
using System.Reflection;
using System.Web; namespace FrameWorkV4.Controls
{
public class SMQGridView : System.Web.UI.WebControls.GridView
{
#region Private Property
private int dataCout;
private int DataCount
{
get
{
if (dataCout == && DataSource != null)
{
if (DataSource is IEnumerable)
{
IEnumerable DataSourceList = (IEnumerable)DataSource;
IEnumerator enumerator = DataSourceList.GetEnumerator();
enumerator.Reset();
while (enumerator.MoveNext())
{
dataCout++;
}
}
if (DataSource is IListSource)
{
IListSource DataSourceList = (IListSource)DataSource;
IList list = DataSourceList.GetList();
dataCout = list.Count;
}
}
return dataCout;
}
}
private int FirstPageIndex
{
get
{
return ;
}
}
private int PreviosPageIndex
{
get
{
return Math.Max(PageIndex - , );
}
}
private int NextPageIndex
{
get
{
return Math.Min(PageIndex + , PageCount - );
}
}
private int LastPageIndex
{
get
{
return PageCount - ;
}
}
//Added by tony at 2010.12.16
private int TotalDataCount
{
get
{
object o = ViewState["TotalDataCount"];
int _dataCout = ;
if (o != null)
{
_dataCout = int.Parse(o.ToString());
}
return _dataCout;
}
set
{
ViewState["TotalDataCount"] = value;
}
}
#endregion #region Public Property
public string OrderByField
{
get
{
object o = ViewState["OrderByField"];
if (o == null)
{
for (int i = ; i < Columns.Count; i++)
{
if (Columns[i].SortExpression.Trim() != string.Empty)
return Columns[i].SortExpression;
}
return string.Empty;
}
return (string)o;
}
set
{
ViewState["OrderByField"] = value;
}
}
public bool OrderByAsc
{
get
{
object o = ViewState["OrderByAsc"];
if (o == null)
{
return true;
}
return (bool)o;
}
set
{
ViewState["OrderByAsc"] = value;
}
}
public string EntityType;
public string PrimaryKeyName;
public string GridViewName;
private bool showSaveChangesButton
{
get
{
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
return true;
}
return false;
}
}
#endregion private bool _isSaveChange = true;
public bool _IsSaveChange
{
get
{
return _isSaveChange;
}
set
{
_isSaveChange = value;
} } //Added by tony at 2010.12.16
public override object DataSource
{
get
{
return base.DataSource;
}
set
{
base.DataSource = value;
int _dataCout = ;
if (value is IEnumerable)
{
IEnumerable DataSourceList = (IEnumerable)value;
IEnumerator enumerator = DataSourceList.GetEnumerator();
enumerator.Reset();
while (enumerator.MoveNext())
{
_dataCout++;
}
}
if (value is IListSource)
{
IListSource DataSourceList = (IListSource)DataSource;
IList list = DataSourceList.GetList();
_dataCout = list.Count;
}
TotalDataCount = _dataCout;
}
} private bool _isAllowSaveChange = false; public bool IsAllowSaveChange
{
get { return _isAllowSaveChange; }
set { _isAllowSaveChange = value; }
} private bool _alwaysShowSaveChange = true; public bool AlwaysShowSaveChange
{
get { return _alwaysShowSaveChange; }
set { _alwaysShowSaveChange = value; }
}
private bool _isAllowAllEdit = false; public bool IsAllowAllEdit
{
get { return _isAllowAllEdit; }
set { _isAllowAllEdit = value; }
} private int _gv_ProgramProductId;
public int GV_ProgramProductId
{
get { return _gv_ProgramProductId; }
set { _gv_ProgramProductId = value; }
} private bool _isProductFeature = false;
public bool IsProductFeature
{
get { return _isProductFeature; }
set { _isProductFeature = value; }
} private bool _isSweepCart = false;
public bool IsSweepCart
{
get { return _isSweepCart; }
set { _isSweepCart = value; }
} private bool _isprogramproductordertype = false;
public bool IsProgramProductOrderType
{
get
{
return _isprogramproductordertype;
}
set
{
_isprogramproductordertype = value;
}
} private bool _isprogramproductcustomertype = false; public bool IsProgramProductCustomerType
{
get
{
return _isprogramproductcustomertype;
}
set
{
_isprogramproductcustomertype = value;
}
} private bool _isReducePrice = false;
public bool IsReducePrice
{
get { return _isReducePrice; }
set { _isReducePrice = value; }
} private int _programproductid = ;
public int ProgramProductId
{
get
{
return _programproductid;
}
set
{
_programproductid = value;
}
} private bool _isAllowPage = true;
public bool IsAllowPage
{
get { return _isAllowPage; }
set { _isAllowPage = value; }
} private bool _updateppstatus = false;
public bool UpdatePPStatus
{
get
{
return _updateppstatus;
}
set
{
_updateppstatus = value;
}
} private bool bHasRecord
{
get
{
try
{
return bool.Parse(ViewState["bHasRecord"].ToString());
}
catch
{
return false;
}
}
set
{
ViewState["bHasRecord"] = value.ToString();
}
} protected override void OnDataBinding(EventArgs e)
{
if (DataSource == null)
{
base.OnDataBinding(e);
return;
} var aa = DataSource as List<SILK2010.Entity>;
if ((DataSource is SILK2010.EntityList) == false)
{
base.OnDataBinding(e);
return;
} SILK2010.EntityList ds = DataSource as SILK2010.EntityList;
if (!string.IsNullOrEmpty(OrderByField))
{
ds.Sort(OrderByField, OrderByAsc);
}
if (!string.IsNullOrEmpty(PrimaryKeyName))
{
this.DataKeyNames = new string[] { PrimaryKeyName };
}
if (!_isAllowPage)
{
this.AllowPaging = false;
}
else
{
this.AllowPaging = true;
} if (ds.Count == )
{
if (string.IsNullOrEmpty(this.EntityType))
{
return;
} Assembly asmb = Assembly.LoadFrom(HttpContext.Current.Server.MapPath("~/Bin/ProTexusModel.dll"));
Entity entity = System.Activator.CreateInstance(asmb.GetType("ProTexus.Model." + EntityType)) as Entity; ds.Add(entity); this.DataSource = ds; this.bHasRecord = false;
}
else
{
this.bHasRecord = true;
}
base.OnDataBinding(e);
} private void SetAdvancedPage(GridViewRowEventArgs e)
{
HtmlGenericControl prolistbottom = new HtmlGenericControl("DIV");
e.Row.Cells[].Controls.Add(prolistbottom);
prolistbottom.Attributes.Add("class", "prolistbottom textindent10");
HtmlGenericControl floatleft = new HtmlGenericControl("DIV");
floatleft.Attributes.Add("class", "floatleft fontwhite");
prolistbottom.Controls.Add(floatleft);
HtmlGenericControl pagesort = new HtmlGenericControl("DIV");
floatleft.Controls.Add(pagesort);
pagesort.Attributes.Add("class", "pagesort"); LiteralControl Pages = new LiteralControl();
Pages.Text = "<b>Page(s):</>";
pagesort.Controls.Add(Pages); LiteralControl _space = new LiteralControl(); //Build "First" and "Previous" button cell.
Button _btnFirst = new Button();
_btnFirst.Text = "First";
_btnFirst.CssClass = "button";
_btnFirst.CommandName = "Pager";
_btnFirst.CommandArgument = FirstPageIndex.ToString();
pagesort.Controls.Add(_btnFirst); Button _btnPrevious = new Button();
_btnPrevious.Text = "Previous";
_btnPrevious.CssClass = "button";
_btnPrevious.CommandName = "Pager";
_btnPrevious.CommandArgument = PreviosPageIndex.ToString();
pagesort.Controls.Add(_btnPrevious); //Build Page list button.
for (int i = ; i < PageCount; i++)
{
if (i > PageIndex - && i < PageIndex + )
{
LinkButton _pageLink = new LinkButton();
int cur = i + ;
if (PageIndex == i)
{
_pageLink.Text = "<b><font size=4>" + cur.ToString() + "</font></>";
}
else
{
_pageLink.Text = "" + cur.ToString() + "";
}
_pageLink.CommandName = "Pager";
_pageLink.CommandArgument = i.ToString();
pagesort.Controls.Add(_pageLink); if (PageIndex == i)
{
_pageLink.Enabled = false;
} _space = new LiteralControl();
_space.Text = " ";
pagesort.Controls.Add(_space);
}
} //Build "Next" and "Last" button cell.
_space = new LiteralControl();
_space.Text = " "; Button _btnNext = new Button();
_btnNext.Text = "Next";
_btnNext.CssClass = "button";
_btnNext.CommandName = "Pager";
_btnNext.CommandArgument = NextPageIndex.ToString();
pagesort.Controls.Add(_btnNext);
pagesort.Controls.Add(_space); Button _btnLast = new Button();
_btnLast.Text = "Last";
_btnLast.CssClass = "button";
_btnLast.CommandName = "Pager";
_btnLast.CommandArgument = LastPageIndex.ToString();
pagesort.Controls.Add(_btnLast);
pagesort.Controls.Add(_space); //Build "Showing Result:" cell.
LiteralControl PageResult = new LiteralControl();
int _currentPageBeginNo = ;
int _currentPageEndNo = ; //if (DataCount != 0)
//{
// _currentPageBeginNo = PageIndex * PageSize + 1;
// _currentPageEndNo = _currentPageBeginNo + PageSize - 1; // if (_currentPageEndNo > DataCount)
// {
// _currentPageEndNo = DataCount;
// }
//} //PageResult.Text = "Showing Result: " + _currentPageBeginNo.ToString() + "-";
//if (IsAllowPage)
//{
// PageResult.Text += _currentPageEndNo.ToString();
//}
//else
//{
// PageResult.Text += DataCount.ToString();
//}
//PageResult.Text += " of " + DataCount.ToString();
if (TotalDataCount != )
{
_currentPageBeginNo = PageIndex * PageSize + ;
_currentPageEndNo = _currentPageBeginNo + PageSize - ; if (_currentPageEndNo > TotalDataCount)
{
_currentPageEndNo = TotalDataCount;
}
} PageResult.Text = "Showing Result: " + _currentPageBeginNo.ToString() + "-";
if (IsAllowPage)
{
PageResult.Text += _currentPageEndNo.ToString();
}
else
{
PageResult.Text += TotalDataCount.ToString();
}
PageResult.Text += " of " + TotalDataCount.ToString();
pagesort.Controls.Add(PageResult); //Build Save Changes Button Cell
HtmlGenericControl floatright = new HtmlGenericControl("DIV");
floatright.Attributes.Add("class", "floatright");
if (showSaveChangesButton && IsAllowSaveChange && AlwaysShowSaveChange)
{
Button btn = new Button();
btn.CommandName = "SaveChanges";
btn.Text = "Save Changes";
btn.CssClass = "buttonBig";
floatright.Controls.Add(btn);
} if (showSaveChangesButton && IsAllowAllEdit)
{
Button btn = new Button();
btn.CommandName = "AllEdit";
btn.Text = "Edit All";
btn.CssClass = "buttonBig";
floatright.Controls.Add(btn);
}
prolistbottom.Controls.Add(floatright); //HtmlGenericControl floatclear = new HtmlGenericControl("DIV");
//floatclear.Attributes.Add("class", "floatclear");
//prolistbottom.Controls.Add(floatclear); if (PageIndex == )
{
_btnFirst.Enabled = false;
_btnPrevious.Enabled = false;
}
if (PageIndex == PageCount - )
{
_btnNext.Enabled = false;
_btnLast.Enabled = false;
}
} protected override void OnRowCreated(GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Footer:
if (this.bHasRecord && Rows.Count != )
{
e.Row.Cells[].ColumnSpan = Columns.Count;
for (int i = ; i < Columns.Count - ; i++)
e.Row.Cells.RemoveAt();
SetAdvancedPage(e);
PagerSettings.Visible = false;
ShowFooter = true;
}
break;
case DataControlRowType.Header:
#region Build Header
for (int i = ; i < Columns.Count; i++)
{
TableCell cell = e.Row.Cells[i];
if (Columns[i].SortExpression.Trim().Length != )
{
LinkButton _headText = new LinkButton();
//_headText.CssClass = HeadCss;
_headText.Text = Columns[i].HeaderText;
_headText.ToolTip = "Sort this column";
_headText.CommandName = "Sort";
_headText.CommandArgument = Columns[i].SortExpression; cell.Controls.Add(_headText); if (OrderByField == Columns[i].SortExpression)
{
ImageButton _headImage = new ImageButton();
_headImage.CommandName = "Sort";
_headImage.CommandArgument = Columns[i].SortExpression;
_headImage.ToolTip = "Sort this column";
if (OrderByAsc == true)
{
_headImage.ImageUrl = "~/Skin/PROTEXUS/Images/SortDirDESC.gif"; }
else
{
_headImage.ImageUrl = "~/Skin/PROTEXUS/Images/SortDirASC.gif";
}
cell.Controls.Add(_headImage);
} }
else
{
LinkButton _headText = new LinkButton();
_headText.Text = Columns[i].HeaderText;
cell.Controls.Add(_headText);
} if (Columns[i] is SMQGridViewField)
{
SMQGridViewField field = Columns[i] as SMQGridViewField;
if (field.CanEdit)
{
if (!IsAllowSaveChange)
IsAllowSaveChange = true; ImageButton _headEdit = new ImageButton();
_headEdit.CommandName = "EditColumn";
_headEdit.CommandArgument = field.DataField;
_headEdit.ToolTip = "Edit this column";
if (field.IsEditing)
{
_headEdit.ImageUrl = "~/Skin/PROTEXUS/Images/icon_edit.gif";
}
else
{
_headEdit.ImageUrl = "~/Skin/PROTEXUS/Images/icon_edit_f2.gif";
}
cell.Controls.Add(_headEdit);
}
if (field.fieldType == FieldType.Delete)
{
Image img = new Image();
img.ImageUrl = "~/Skin/PROTEXUS/Images/icon_del.gif";
cell.Controls.Add(img);
CheckBox cbx = new CheckBox();
cell.Controls.Add(cbx);
}
if (cell.Controls.Count == )
{
LiteralControl lbl = new LiteralControl();
lbl.Text = field.HeaderText;
cell.Controls.Add(lbl);
}
}
}
#endregion
break;
default:
if (this.bHasRecord)
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
base.OnRowCreated(e);
} break;
}
}
public void SetNoRecordRow(GridViewRowEventArgs e)
{
//if (!this.bHasRecord)
//{
// for (int i = 0; i < e.Row.Cells.Count; i++)
// {
// e.Row.Cells[i].Text = " ";
// }
//}
} protected override void OnRowCommand(GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Sort":
OrderByField = e.CommandArgument.ToString();
OrderByAsc = !OrderByAsc;
break;
case "Pager":
PageIndex = int.Parse(e.CommandArgument.ToString());
break;
case "EditColumn":
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fld = field as SMQGridViewField;
if (fld.DataField == e.CommandArgument.ToString())
fld.IsEditing = !fld.IsEditing;
}
}
break;
case "AllEdit":
{
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fld = field as SMQGridViewField;
fld.IsEditing = true;
}
}
break;
}
case "SaveChanges":
if (_IsSaveChange)
{
if (!SaveChanges())
return;
}
break;
}
base.OnRowCommand(e);
} protected override void Render(HtmlTextWriter writer)
{
this.Style.Add("border-collapse", "separate!important");
writer.Write("<div class=\"proList\"><div class=\"prolistTop fontbold textindent10\">" + GridViewName + "</div>");
base.Render(writer);
writer.Write("</div>"); ScriptManager.RegisterStartupScript(this, this.GetType(), this.UniqueID, this.SetGVNoRecordScript(), true); } private bool SaveChanges()
{
if (string.IsNullOrEmpty(EntityType))
return false; #region Validate has smq field.
bool hasSMQField = false;
foreach (DataControlField field in this.Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fie = field as SMQGridViewField;
if (fie.IsEditing || fie.fieldType == FieldType.Delete)
hasSMQField = true;
}
}
if (!hasSMQField)
return false;
#endregion EntityList DeleteList = new EntityList();
EntityList UpdateList = new EntityList();
foreach (GridViewRow row in Rows)
{
int PrimaryKeyValue = int.Parse(DataKeys[row.RowIndex].Value.ToString()); Entity entity = System.Activator.CreateInstance(Type.GetType("ProTexus.Model." + EntityType)) as Entity; #region Get Table Name
PropertyInfo[] properties = entity.GetType().GetProperties();
foreach (BindingClassAttribute attr in entity.GetType().GetCustomAttributes(typeof(BindingClassAttribute), true))
{
entity.TableName = attr.TableName;
break;
}
#endregion #region Get Original Data
string Usp_SQL = "SELECT top 1 * FROM [" + entity.TableName + "] WHERE [" + PrimaryKeyName + "]=" + PrimaryKeyValue.ToString();
ReturnValue _result = entity.getEntity(Usp_SQL);
if (!_result.Success)
{
return false;
}
entity = _result.Object;
#endregion #region Set New Data
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is SMQGridViewField)
{ SMQGridViewField field = cell.ContainingField as SMQGridViewField; if (field.fieldType == FieldType.Delete)
{
CheckBox cbx = cell.Controls[] as CheckBox;
if (cbx.Checked)
{
entity.GetType().GetProperty(PrimaryKeyName).SetValue(entity, PrimaryKeyValue, null);
DeleteList.Add(entity);
goto NewRow;
}
}
else
{
if (field.IsEditing)
{
if (field.fieldType == FieldType.DateTime)
{
//DateSelector dsl = cell.Controls[0] as DateSelector;
//if (dsl.HasDateTime)
//{
// entity.GetType().GetProperty(field.DataField).SetValue(entity, dsl.DateTime, null);
//}
//else
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a datetime</div>"));
// return false;
//}
}
if (field.fieldType == FieldType.CheckBox)
{
CheckBox cbx = cell.Controls[] as CheckBox;
entity.GetType().GetProperty(field.DataField).SetValue(entity, cbx.Checked, null);
}
if (field.fieldType == FieldType.CheckBoxFeature)
{
CheckBox cbx = cell.Controls[] as CheckBox;
string statusId = "Status";
entity.GetType().GetProperty(statusId).SetValue(entity, cbx.Checked, null);
} if (field.fieldType == FieldType.Status)
{
DropDownList ddl = cell.Controls[] as DropDownList;
string contentStatusName = "ContentStatusId";
if (!string.IsNullOrEmpty(field.ContentStatusName))
{
contentStatusName = field.ContentStatusName;
}
entity.GetType().GetProperty(contentStatusName).SetValue(entity, int.Parse(ddl.SelectedValue), null);
} if (field.fieldType == FieldType.PPStatus)
{
DropDownList ddl = cell.Controls[] as DropDownList;
string contentStatusName = "ContentStatusId";
if (!string.IsNullOrEmpty(field.ContentStatusName))
{
contentStatusName = field.ContentStatusName;
}
entity.GetType().GetProperty(contentStatusName).SetValue(entity, int.Parse(ddl.SelectedValue), null);
} if (field.fieldType == FieldType.Feature)
{
DropDownList ddl_Feature = cell.Controls[] as DropDownList;
string locationId = "Location";
if (!string.IsNullOrEmpty(field.FeatureLocation))
{
locationId = field.FeatureLocation;
}
entity.GetType().GetProperty(locationId).SetValue(entity, int.Parse(ddl_Feature.SelectedValue), null);
} if (field.fieldType == FieldType.Int)
{
TextBox txt = cell.Controls[] as TextBox;
if (SILK2010.Utilities.isInteger(txt.Text))
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, int.Parse(txt.Text), null);
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a integer</div>"));
return false;
}
} if (field.fieldType == FieldType.MaxQty)
{
TextBox txt = cell.Controls[] as TextBox; if (!string.IsNullOrEmpty(txt.Text))
{
if (SILK2010.Utilities.IsDouble(txt.Text.Trim()))
{
//if (int.Parse(txt.Text.Trim()) <= 0)
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Duration's data must larger than 0</div>"));
// return false; //}
//else
//{
entity.GetType().GetProperty(field.DataField).SetValue(entity, int.Parse(txt.Text), null);
//}
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number</div>"));
return false;
}
}
else
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, null, null); } }
if (field.fieldType == FieldType.Double)
{
TextBox txt = cell.Controls[] as TextBox;
if (SILK2010.Utilities.IsDouble(txt.Text))
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, double.Parse(txt.Text), null);
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number</div>"));
return false;
}
}
if (field.fieldType == FieldType.TextBox || field.fieldType == FieldType.LinkButton)
{
TextBox txt = cell.Controls[] as TextBox;
entity.GetType().GetProperty(field.DataField).SetValue(entity, txt.Text, null);
}
if (field.fieldType == FieldType.Duration)
{
TextBox txt_Duration = cell.Controls[] as TextBox;
DropDownList ddl_TimeType = cell.Controls[] as DropDownList; if (!string.IsNullOrEmpty(txt_Duration.Text))
{
if (SILK2010.Utilities.IsDouble(txt_Duration.Text.Trim()))
{
//if (double.Parse(txt_Duration.Text.Trim()) <= 0)
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Duration's data must larger than 0</div>"));
// return false;
//}
//else
//{
if (ddl_TimeType.SelectedValue == "Order")
{
entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(""), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null); }
else
{ entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(txt_Duration.Text.Trim()), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null);
}
//} }
else
{ cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number for Duration field</div>"));
return false; }
}
else
{
if (ddl_TimeType.SelectedValue == "Order")
{
entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(""), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null); }
else
{
entity.GetType().GetProperty("Duration").SetValue(entity, null, null);
entity.GetType().GetProperty("TimeType").SetValue(entity, null, null);
} } }
}
}
}
} UpdateList.Add(entity); //UpdateList.Add(entity); NewRow:
continue; #endregion } #region Save New Data Entity entityForTrans = System.Activator.CreateInstance(Type.GetType("ZstoreAdmin.Model." + EntityType)) as Entity; Transaction trans = new Transaction(entityForTrans.DataConnectProviders); ReturnValue result = new ReturnValue(); foreach (Entity entity in DeleteList)
{
result = entity.Delete(trans);
if (!result.Success)
{
if (trans.InTransaction)
trans.RollbackTransaction();
return false;
}
} foreach (Entity entity in UpdateList)
{
result = entity.Update(trans);
if (!result.Success)
{
if (trans.InTransaction)
trans.RollbackTransaction();
return false;
}
} trans.CommitTransaction(); #endregion #region Restore Grid State foreach (DataControlField field in this.Columns)
{
if (field is SMQGridViewField)
{
((SMQGridViewField)field).IsEditing = false;
}
} #endregion return true;
} public bool SaveChangesAfterValidation()
{
return this.SaveChanges();
} private string SetGVNoRecordScript()
{ if (this.bHasRecord)
{
return "";
} StringBuilder sb = new StringBuilder(); sb.Append("\r\n function SetGVNoRecord" + this.ClientID + "(){");
sb.Append("\r\n var gv = document.getElementById('" + this.ClientID + "');");
sb.Append("\r\n if(gv == null){ return;}");
sb.Append("\r\n var rowCount = gv.rows.length;");
sb.Append("\r\n for(var i = rowCount - 1 ; i > 0;i--){");
sb.Append("\r\n if(i == 1){");
sb.Append("\r\n for(var j =0 ; j < gv.rows[i].cells.length;j++){");
sb.Append("\r\n gv.rows[i].cells[j].innerHTML=' ';");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n else {");
sb.Append("\r\n gv.deleteRow(i);");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n SetGVNoRecord" + this.ClientID + "();"); return sb.ToString();
}
}
}
GridView
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.Design;
using System.ComponentModel;
using SILK2010;
using System.Reflection;
using System.Web; namespace FrameWorkV4.Controls
{
public class SMQGridView : System.Web.UI.WebControls.GridView
{
#region Private Property
private int dataCout;
private int DataCount
{
get
{
if (dataCout == && DataSource != null)
{
if (DataSource is IEnumerable)
{
IEnumerable DataSourceList = (IEnumerable)DataSource;
IEnumerator enumerator = DataSourceList.GetEnumerator();
enumerator.Reset();
while (enumerator.MoveNext())
{
dataCout++;
}
}
if (DataSource is IListSource)
{
IListSource DataSourceList = (IListSource)DataSource;
IList list = DataSourceList.GetList();
dataCout = list.Count;
}
}
return dataCout;
}
}
private int FirstPageIndex
{
get
{
return ;
}
}
private int PreviosPageIndex
{
get
{
return Math.Max(PageIndex - , );
}
}
private int NextPageIndex
{
get
{
return Math.Min(PageIndex + , PageCount - );
}
}
private int LastPageIndex
{
get
{
return PageCount - ;
}
}
//Added by tony at 2010.12.16
private int TotalDataCount
{
get
{
object o = ViewState["TotalDataCount"];
int _dataCout = ;
if (o != null)
{
_dataCout = int.Parse(o.ToString());
}
return _dataCout;
}
set
{
ViewState["TotalDataCount"] = value;
}
}
#endregion #region Public Property
public string OrderByField
{
get
{
object o = ViewState["OrderByField"];
if (o == null)
{
for (int i = ; i < Columns.Count; i++)
{
if (Columns[i].SortExpression.Trim() != string.Empty)
return Columns[i].SortExpression;
}
return string.Empty;
}
return (string)o;
}
set
{
ViewState["OrderByField"] = value;
}
}
public bool OrderByAsc
{
get
{
object o = ViewState["OrderByAsc"];
if (o == null)
{
return true;
}
return (bool)o;
}
set
{
ViewState["OrderByAsc"] = value;
}
}
public string EntityType;
public string PrimaryKeyName;
public string GridViewName;
private bool showSaveChangesButton
{
get
{
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
return true;
}
return false;
}
}
#endregion private bool _isSaveChange = true;
public bool _IsSaveChange
{
get
{
return _isSaveChange;
}
set
{
_isSaveChange = value;
} } //Added by tony at 2010.12.16
public override object DataSource
{
get
{
return base.DataSource;
}
set
{
base.DataSource = value;
int _dataCout = ;
if (value is IEnumerable)
{
IEnumerable DataSourceList = (IEnumerable)value;
IEnumerator enumerator = DataSourceList.GetEnumerator();
enumerator.Reset();
while (enumerator.MoveNext())
{
_dataCout++;
}
}
if (value is IListSource)
{
IListSource DataSourceList = (IListSource)DataSource;
IList list = DataSourceList.GetList();
_dataCout = list.Count;
}
TotalDataCount = _dataCout;
}
} private bool _isAllowSaveChange = false; public bool IsAllowSaveChange
{
get { return _isAllowSaveChange; }
set { _isAllowSaveChange = value; }
} private bool _alwaysShowSaveChange = true; public bool AlwaysShowSaveChange
{
get { return _alwaysShowSaveChange; }
set { _alwaysShowSaveChange = value; }
}
private bool _isAllowAllEdit = false; public bool IsAllowAllEdit
{
get { return _isAllowAllEdit; }
set { _isAllowAllEdit = value; }
} private int _gv_ProgramProductId;
public int GV_ProgramProductId
{
get { return _gv_ProgramProductId; }
set { _gv_ProgramProductId = value; }
} private bool _isProductFeature = false;
public bool IsProductFeature
{
get { return _isProductFeature; }
set { _isProductFeature = value; }
} private bool _isSweepCart = false;
public bool IsSweepCart
{
get { return _isSweepCart; }
set { _isSweepCart = value; }
} private bool _isprogramproductordertype = false;
public bool IsProgramProductOrderType
{
get
{
return _isprogramproductordertype;
}
set
{
_isprogramproductordertype = value;
}
} private bool _isprogramproductcustomertype = false; public bool IsProgramProductCustomerType
{
get
{
return _isprogramproductcustomertype;
}
set
{
_isprogramproductcustomertype = value;
}
} private bool _isReducePrice = false;
public bool IsReducePrice
{
get { return _isReducePrice; }
set { _isReducePrice = value; }
} private int _programproductid = ;
public int ProgramProductId
{
get
{
return _programproductid;
}
set
{
_programproductid = value;
}
} private bool _isAllowPage = true;
public bool IsAllowPage
{
get { return _isAllowPage; }
set { _isAllowPage = value; }
} private bool _updateppstatus = false;
public bool UpdatePPStatus
{
get
{
return _updateppstatus;
}
set
{
_updateppstatus = value;
}
} private bool bHasRecord
{
get
{
try
{
return bool.Parse(ViewState["bHasRecord"].ToString());
}
catch
{
return false;
}
}
set
{
ViewState["bHasRecord"] = value.ToString();
}
} protected override void OnDataBinding(EventArgs e)
{
if (DataSource == null)
{
base.OnDataBinding(e);
return;
} var aa = DataSource as List<SILK2010.Entity>;
if ((DataSource is SILK2010.EntityList) == false)
{
base.OnDataBinding(e);
return;
} SILK2010.EntityList ds = DataSource as SILK2010.EntityList;
if (!string.IsNullOrEmpty(OrderByField))
{
ds.Sort(OrderByField, OrderByAsc);
}
if (!string.IsNullOrEmpty(PrimaryKeyName))
{
this.DataKeyNames = new string[] { PrimaryKeyName };
}
if (!_isAllowPage)
{
this.AllowPaging = false;
}
else
{
this.AllowPaging = true;
} if (ds.Count == )
{
if (string.IsNullOrEmpty(this.EntityType))
{
return;
} Assembly asmb = Assembly.LoadFrom(HttpContext.Current.Server.MapPath("~/Bin/ProTexusModel.dll"));
Entity entity = System.Activator.CreateInstance(asmb.GetType("ProTexus.Model." + EntityType)) as Entity; ds.Add(entity); this.DataSource = ds; this.bHasRecord = false;
}
else
{
this.bHasRecord = true;
}
base.OnDataBinding(e);
} private void SetAdvancedPage(GridViewRowEventArgs e)
{
HtmlGenericControl prolistbottom = new HtmlGenericControl("DIV");
e.Row.Cells[].Controls.Add(prolistbottom);
prolistbottom.Attributes.Add("class", "prolistbottom textindent10");
HtmlGenericControl floatleft = new HtmlGenericControl("DIV");
floatleft.Attributes.Add("class", "floatleft fontwhite");
prolistbottom.Controls.Add(floatleft);
HtmlGenericControl pagesort = new HtmlGenericControl("DIV");
floatleft.Controls.Add(pagesort);
pagesort.Attributes.Add("class", "pagesort"); LiteralControl Pages = new LiteralControl();
Pages.Text = "<b>Page(s):</>";
pagesort.Controls.Add(Pages); LiteralControl _space = new LiteralControl(); //Build "First" and "Previous" button cell.
Button _btnFirst = new Button();
_btnFirst.Text = "First";
_btnFirst.CssClass = "button";
_btnFirst.CommandName = "Pager";
_btnFirst.CommandArgument = FirstPageIndex.ToString();
pagesort.Controls.Add(_btnFirst); Button _btnPrevious = new Button();
_btnPrevious.Text = "Previous";
_btnPrevious.CssClass = "button";
_btnPrevious.CommandName = "Pager";
_btnPrevious.CommandArgument = PreviosPageIndex.ToString();
pagesort.Controls.Add(_btnPrevious); //Build Page list button.
for (int i = ; i < PageCount; i++)
{
if (i > PageIndex - && i < PageIndex + )
{
LinkButton _pageLink = new LinkButton();
int cur = i + ;
if (PageIndex == i)
{
_pageLink.Text = "<b><font size=4>" + cur.ToString() + "</font></>";
}
else
{
_pageLink.Text = "" + cur.ToString() + "";
}
_pageLink.CommandName = "Pager";
_pageLink.CommandArgument = i.ToString();
pagesort.Controls.Add(_pageLink); if (PageIndex == i)
{
_pageLink.Enabled = false;
} _space = new LiteralControl();
_space.Text = " ";
pagesort.Controls.Add(_space);
}
} //Build "Next" and "Last" button cell.
_space = new LiteralControl();
_space.Text = " "; Button _btnNext = new Button();
_btnNext.Text = "Next";
_btnNext.CssClass = "button";
_btnNext.CommandName = "Pager";
_btnNext.CommandArgument = NextPageIndex.ToString();
pagesort.Controls.Add(_btnNext);
pagesort.Controls.Add(_space); Button _btnLast = new Button();
_btnLast.Text = "Last";
_btnLast.CssClass = "button";
_btnLast.CommandName = "Pager";
_btnLast.CommandArgument = LastPageIndex.ToString();
pagesort.Controls.Add(_btnLast);
pagesort.Controls.Add(_space); //Build "Showing Result:" cell.
LiteralControl PageResult = new LiteralControl();
int _currentPageBeginNo = ;
int _currentPageEndNo = ; //if (DataCount != 0)
//{
// _currentPageBeginNo = PageIndex * PageSize + 1;
// _currentPageEndNo = _currentPageBeginNo + PageSize - 1; // if (_currentPageEndNo > DataCount)
// {
// _currentPageEndNo = DataCount;
// }
//} //PageResult.Text = "Showing Result: " + _currentPageBeginNo.ToString() + "-";
//if (IsAllowPage)
//{
// PageResult.Text += _currentPageEndNo.ToString();
//}
//else
//{
// PageResult.Text += DataCount.ToString();
//}
//PageResult.Text += " of " + DataCount.ToString();
if (TotalDataCount != )
{
_currentPageBeginNo = PageIndex * PageSize + ;
_currentPageEndNo = _currentPageBeginNo + PageSize - ; if (_currentPageEndNo > TotalDataCount)
{
_currentPageEndNo = TotalDataCount;
}
} PageResult.Text = "Showing Result: " + _currentPageBeginNo.ToString() + "-";
if (IsAllowPage)
{
PageResult.Text += _currentPageEndNo.ToString();
}
else
{
PageResult.Text += TotalDataCount.ToString();
}
PageResult.Text += " of " + TotalDataCount.ToString();
pagesort.Controls.Add(PageResult); //Build Save Changes Button Cell
HtmlGenericControl floatright = new HtmlGenericControl("DIV");
floatright.Attributes.Add("class", "floatright");
if (showSaveChangesButton && IsAllowSaveChange && AlwaysShowSaveChange)
{
Button btn = new Button();
btn.CommandName = "SaveChanges";
btn.Text = "Save Changes";
btn.CssClass = "buttonBig";
floatright.Controls.Add(btn);
} if (showSaveChangesButton && IsAllowAllEdit)
{
Button btn = new Button();
btn.CommandName = "AllEdit";
btn.Text = "Edit All";
btn.CssClass = "buttonBig";
floatright.Controls.Add(btn);
}
prolistbottom.Controls.Add(floatright); //HtmlGenericControl floatclear = new HtmlGenericControl("DIV");
//floatclear.Attributes.Add("class", "floatclear");
//prolistbottom.Controls.Add(floatclear); if (PageIndex == )
{
_btnFirst.Enabled = false;
_btnPrevious.Enabled = false;
}
if (PageIndex == PageCount - )
{
_btnNext.Enabled = false;
_btnLast.Enabled = false;
}
} protected override void OnRowCreated(GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Footer:
if (this.bHasRecord && Rows.Count != )
{
e.Row.Cells[].ColumnSpan = Columns.Count;
for (int i = ; i < Columns.Count - ; i++)
e.Row.Cells.RemoveAt();
SetAdvancedPage(e);
PagerSettings.Visible = false;
ShowFooter = true;
}
break;
case DataControlRowType.Header:
#region Build Header
for (int i = ; i < Columns.Count; i++)
{
TableCell cell = e.Row.Cells[i];
if (Columns[i].SortExpression.Trim().Length != )
{
LinkButton _headText = new LinkButton();
//_headText.CssClass = HeadCss;
_headText.Text = Columns[i].HeaderText;
_headText.ToolTip = "Sort this column";
_headText.CommandName = "Sort";
_headText.CommandArgument = Columns[i].SortExpression; cell.Controls.Add(_headText); if (OrderByField == Columns[i].SortExpression)
{
ImageButton _headImage = new ImageButton();
_headImage.CommandName = "Sort";
_headImage.CommandArgument = Columns[i].SortExpression;
_headImage.ToolTip = "Sort this column";
if (OrderByAsc == true)
{
_headImage.ImageUrl = "~/Skin/PROTEXUS/Images/SortDirDESC.gif"; }
else
{
_headImage.ImageUrl = "~/Skin/PROTEXUS/Images/SortDirASC.gif";
}
cell.Controls.Add(_headImage);
} }
else
{
LinkButton _headText = new LinkButton();
_headText.Text = Columns[i].HeaderText;
cell.Controls.Add(_headText);
} if (Columns[i] is SMQGridViewField)
{
SMQGridViewField field = Columns[i] as SMQGridViewField;
if (field.CanEdit)
{
if (!IsAllowSaveChange)
IsAllowSaveChange = true; ImageButton _headEdit = new ImageButton();
_headEdit.CommandName = "EditColumn";
_headEdit.CommandArgument = field.DataField;
_headEdit.ToolTip = "Edit this column";
if (field.IsEditing)
{
_headEdit.ImageUrl = "~/Skin/PROTEXUS/Images/icon_edit.gif";
}
else
{
_headEdit.ImageUrl = "~/Skin/PROTEXUS/Images/icon_edit_f2.gif";
}
cell.Controls.Add(_headEdit);
}
if (field.fieldType == FieldType.Delete)
{
Image img = new Image();
img.ImageUrl = "~/Skin/PROTEXUS/Images/icon_del.gif";
cell.Controls.Add(img);
CheckBox cbx = new CheckBox();
cell.Controls.Add(cbx);
}
if (cell.Controls.Count == )
{
LiteralControl lbl = new LiteralControl();
lbl.Text = field.HeaderText;
cell.Controls.Add(lbl);
}
}
}
#endregion
break;
default:
if (this.bHasRecord)
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
base.OnRowCreated(e);
} break;
}
}
public void SetNoRecordRow(GridViewRowEventArgs e)
{
//if (!this.bHasRecord)
//{
// for (int i = 0; i < e.Row.Cells.Count; i++)
// {
// e.Row.Cells[i].Text = " ";
// }
//}
} protected override void OnRowCommand(GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Sort":
OrderByField = e.CommandArgument.ToString();
OrderByAsc = !OrderByAsc;
break;
case "Pager":
PageIndex = int.Parse(e.CommandArgument.ToString());
break;
case "EditColumn":
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fld = field as SMQGridViewField;
if (fld.DataField == e.CommandArgument.ToString())
fld.IsEditing = !fld.IsEditing;
}
}
break;
case "AllEdit":
{
foreach (DataControlField field in Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fld = field as SMQGridViewField;
fld.IsEditing = true;
}
}
break;
}
case "SaveChanges":
if (_IsSaveChange)
{
if (!SaveChanges())
return;
}
break;
}
base.OnRowCommand(e);
} protected override void Render(HtmlTextWriter writer)
{
this.Style.Add("border-collapse", "separate!important");
writer.Write("<div class=\"proList\"><div class=\"prolistTop fontbold textindent10\">" + GridViewName + "</div>");
base.Render(writer);
writer.Write("</div>"); ScriptManager.RegisterStartupScript(this, this.GetType(), this.UniqueID, this.SetGVNoRecordScript(), true); } private bool SaveChanges()
{
if (string.IsNullOrEmpty(EntityType))
return false; #region Validate has smq field.
bool hasSMQField = false;
foreach (DataControlField field in this.Columns)
{
if (field is SMQGridViewField)
{
SMQGridViewField fie = field as SMQGridViewField;
if (fie.IsEditing || fie.fieldType == FieldType.Delete)
hasSMQField = true;
}
}
if (!hasSMQField)
return false;
#endregion EntityList DeleteList = new EntityList();
EntityList UpdateList = new EntityList();
foreach (GridViewRow row in Rows)
{
int PrimaryKeyValue = int.Parse(DataKeys[row.RowIndex].Value.ToString()); Entity entity = System.Activator.CreateInstance(Type.GetType("ProTexus.Model." + EntityType)) as Entity; #region Get Table Name
PropertyInfo[] properties = entity.GetType().GetProperties();
foreach (BindingClassAttribute attr in entity.GetType().GetCustomAttributes(typeof(BindingClassAttribute), true))
{
entity.TableName = attr.TableName;
break;
}
#endregion #region Get Original Data
string Usp_SQL = "SELECT top 1 * FROM [" + entity.TableName + "] WHERE [" + PrimaryKeyName + "]=" + PrimaryKeyValue.ToString();
ReturnValue _result = entity.getEntity(Usp_SQL);
if (!_result.Success)
{
return false;
}
entity = _result.Object;
#endregion #region Set New Data
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is SMQGridViewField)
{ SMQGridViewField field = cell.ContainingField as SMQGridViewField; if (field.fieldType == FieldType.Delete)
{
CheckBox cbx = cell.Controls[] as CheckBox;
if (cbx.Checked)
{
entity.GetType().GetProperty(PrimaryKeyName).SetValue(entity, PrimaryKeyValue, null);
DeleteList.Add(entity);
goto NewRow;
}
}
else
{
if (field.IsEditing)
{
if (field.fieldType == FieldType.DateTime)
{
//DateSelector dsl = cell.Controls[0] as DateSelector;
//if (dsl.HasDateTime)
//{
// entity.GetType().GetProperty(field.DataField).SetValue(entity, dsl.DateTime, null);
//}
//else
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a datetime</div>"));
// return false;
//}
}
if (field.fieldType == FieldType.CheckBox)
{
CheckBox cbx = cell.Controls[] as CheckBox;
entity.GetType().GetProperty(field.DataField).SetValue(entity, cbx.Checked, null);
}
if (field.fieldType == FieldType.CheckBoxFeature)
{
CheckBox cbx = cell.Controls[] as CheckBox;
string statusId = "Status";
entity.GetType().GetProperty(statusId).SetValue(entity, cbx.Checked, null);
} if (field.fieldType == FieldType.Status)
{
DropDownList ddl = cell.Controls[] as DropDownList;
string contentStatusName = "ContentStatusId";
if (!string.IsNullOrEmpty(field.ContentStatusName))
{
contentStatusName = field.ContentStatusName;
}
entity.GetType().GetProperty(contentStatusName).SetValue(entity, int.Parse(ddl.SelectedValue), null);
} if (field.fieldType == FieldType.PPStatus)
{
DropDownList ddl = cell.Controls[] as DropDownList;
string contentStatusName = "ContentStatusId";
if (!string.IsNullOrEmpty(field.ContentStatusName))
{
contentStatusName = field.ContentStatusName;
}
entity.GetType().GetProperty(contentStatusName).SetValue(entity, int.Parse(ddl.SelectedValue), null);
} if (field.fieldType == FieldType.Feature)
{
DropDownList ddl_Feature = cell.Controls[] as DropDownList;
string locationId = "Location";
if (!string.IsNullOrEmpty(field.FeatureLocation))
{
locationId = field.FeatureLocation;
}
entity.GetType().GetProperty(locationId).SetValue(entity, int.Parse(ddl_Feature.SelectedValue), null);
} if (field.fieldType == FieldType.Int)
{
TextBox txt = cell.Controls[] as TextBox;
if (SILK2010.Utilities.isInteger(txt.Text))
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, int.Parse(txt.Text), null);
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a integer</div>"));
return false;
}
} if (field.fieldType == FieldType.MaxQty)
{
TextBox txt = cell.Controls[] as TextBox; if (!string.IsNullOrEmpty(txt.Text))
{
if (SILK2010.Utilities.IsDouble(txt.Text.Trim()))
{
//if (int.Parse(txt.Text.Trim()) <= 0)
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Duration's data must larger than 0</div>"));
// return false; //}
//else
//{
entity.GetType().GetProperty(field.DataField).SetValue(entity, int.Parse(txt.Text), null);
//}
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number</div>"));
return false;
}
}
else
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, null, null); } }
if (field.fieldType == FieldType.Double)
{
TextBox txt = cell.Controls[] as TextBox;
if (SILK2010.Utilities.IsDouble(txt.Text))
{
entity.GetType().GetProperty(field.DataField).SetValue(entity, double.Parse(txt.Text), null);
}
else
{
cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number</div>"));
return false;
}
}
if (field.fieldType == FieldType.TextBox || field.fieldType == FieldType.LinkButton)
{
TextBox txt = cell.Controls[] as TextBox;
entity.GetType().GetProperty(field.DataField).SetValue(entity, txt.Text, null);
}
if (field.fieldType == FieldType.Duration)
{
TextBox txt_Duration = cell.Controls[] as TextBox;
DropDownList ddl_TimeType = cell.Controls[] as DropDownList; if (!string.IsNullOrEmpty(txt_Duration.Text))
{
if (SILK2010.Utilities.IsDouble(txt_Duration.Text.Trim()))
{
//if (double.Parse(txt_Duration.Text.Trim()) <= 0)
//{
// cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Duration's data must larger than 0</div>"));
// return false;
//}
//else
//{
if (ddl_TimeType.SelectedValue == "Order")
{
entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(""), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null); }
else
{ entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(txt_Duration.Text.Trim()), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null);
}
//} }
else
{ cell.Controls.Add(new LiteralControl("<div class=\"MessageSummary\">Please provide a number for Duration field</div>"));
return false; }
}
else
{
if (ddl_TimeType.SelectedValue == "Order")
{
entity.GetType().GetProperty("Duration").SetValue(entity, double.Parse(""), null);
entity.GetType().GetProperty("TimeType").SetValue(entity, ddl_TimeType.SelectedValue, null); }
else
{
entity.GetType().GetProperty("Duration").SetValue(entity, null, null);
entity.GetType().GetProperty("TimeType").SetValue(entity, null, null);
} } }
}
}
}
} UpdateList.Add(entity); //UpdateList.Add(entity); NewRow:
continue; #endregion } #region Save New Data Entity entityForTrans = System.Activator.CreateInstance(Type.GetType("ZstoreAdmin.Model." + EntityType)) as Entity; Transaction trans = new Transaction(entityForTrans.DataConnectProviders); ReturnValue result = new ReturnValue(); foreach (Entity entity in DeleteList)
{
result = entity.Delete(trans);
if (!result.Success)
{
if (trans.InTransaction)
trans.RollbackTransaction();
return false;
}
} foreach (Entity entity in UpdateList)
{
result = entity.Update(trans);
if (!result.Success)
{
if (trans.InTransaction)
trans.RollbackTransaction();
return false;
}
} trans.CommitTransaction(); #endregion #region Restore Grid State foreach (DataControlField field in this.Columns)
{
if (field is SMQGridViewField)
{
((SMQGridViewField)field).IsEditing = false;
}
} #endregion return true;
} public bool SaveChangesAfterValidation()
{
return this.SaveChanges();
} private string SetGVNoRecordScript()
{ if (this.bHasRecord)
{
return "";
} StringBuilder sb = new StringBuilder(); sb.Append("\r\n function SetGVNoRecord" + this.ClientID + "(){");
sb.Append("\r\n var gv = document.getElementById('" + this.ClientID + "');");
sb.Append("\r\n if(gv == null){ return;}");
sb.Append("\r\n var rowCount = gv.rows.length;");
sb.Append("\r\n for(var i = rowCount - 1 ; i > 0;i--){");
sb.Append("\r\n if(i == 1){");
sb.Append("\r\n for(var j =0 ; j < gv.rows[i].cells.length;j++){");
sb.Append("\r\n gv.rows[i].cells[j].innerHTML=' ';");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n else {");
sb.Append("\r\n gv.deleteRow(i);");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n }");
sb.Append("\r\n SetGVNoRecord" + this.ClientID + "();"); return sb.ToString();
}
}
}
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.Design;
using System.ComponentModel;
using SILK2010; namespace FrameWorkV4.Controls
{
public class SMQGridViewField : BoundField
{
public bool CanEdit;
public bool IsEditing
{
get
{
object o = ViewState["IsEditing"];
if (o == null)
{
return false;
}
return (bool)o;
}
set
{
ViewState["IsEditing"] = value;
}
}
public FieldType fieldType;
public string ContentStatusName;
public string FeatureLocation;
public string StatusName; public SMQGridViewField()
{ } protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
base.InitializeDataCell(cell, rowState);
if (IsEditing)
{
switch (fieldType)
{
case FieldType.DateTime:
//DateSelector dsl = new DateSelector();
//cell.Controls.Add(dsl);
break;
case FieldType.Status:
DropDownList ddl = new DropDownList();
ddl.Items.Add(new ListItem("Active", ""));
ddl.Items.Add(new ListItem("Pending", ""));
ddl.Items.Add(new ListItem("Inactive", ""));
ddl.Attributes.Add("onchange", "TableViewer_Mark_Field_Altered(this);");
ddl.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(ddl);
break;
case FieldType.Feature:
DropDownList ddl_Feature = new DropDownList();
ddl_Feature.Items.Add(new ListItem("Top", ""));
ddl_Feature.Items.Add(new ListItem("Bottom", ""));
ddl_Feature.Attributes.Add("onchange", "TableViewer_Mark_Field_Altered(this);");
ddl_Feature.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(ddl_Feature);
break;
case FieldType.CheckBox:
CheckBox cbx = new CheckBox();
cbx.Attributes.Add("onclick", "TableViewer_Mark_Field_Altered(this);");
cbx.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(cbx);
break;
case FieldType.CheckBoxFeature:
CheckBox cbxfeature = new CheckBox();
cbxfeature.Attributes.Add("onclick", "TableViewer_Mark_Field_Altered(this);");
cbxfeature.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(cbxfeature);
break;
case FieldType.MaxQty:
TextBox txtMaxQty = new TextBox();
txtMaxQty.Width = new Unit("40%");
txtMaxQty.Attributes.Add("onkeyup", "TableViewer_Mark_Field_Altered(this);");
txtMaxQty.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(txtMaxQty);
break;
case FieldType.Duration:
TextBox txtDuration = new TextBox();
txtDuration.Width = new Unit("40%");
txtDuration.Attributes.Add("onkeyup", "TableViewer_Mark_Field_Altered(this);");
txtDuration.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(txtDuration);
DropDownList ddl_TimeType = new DropDownList();
ddl_TimeType.Items.Insert(, new ListItem("Seconds", "Seconds"));
ddl_TimeType.Items.Insert(, new ListItem("Minutes", "Minutes"));
ddl_TimeType.Items.Insert(, new ListItem("Hours", "Hours"));
ddl_TimeType.Items.Insert(, new ListItem("Days", "Days"));
ddl_TimeType.Items.Insert(, new ListItem("Months", "Months"));
ddl_TimeType.Items.Insert(, new ListItem("Years", "Years"));
ddl_TimeType.Items.Insert(, new ListItem("Lifetime", "Lifetime"));
ddl_TimeType.Items.Insert(, new ListItem("Order", "Order"));
ddl_TimeType.Attributes.Add("onchange", "TableViewer_Mark_Field_Altered(this);");
ddl_TimeType.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(ddl_TimeType);
break;
case FieldType.PPStatus:
DropDownList ddl_ppstatus = new DropDownList();
ddl_ppstatus.Items.Add(new ListItem("Active", ""));
ddl_ppstatus.Items.Add(new ListItem("Pending", ""));
ddl_ppstatus.Items.Add(new ListItem("Inactive", ""));
ddl_ppstatus.Attributes.Add("onchange", "TableViewer_Mark_Field_Altered(this);");
ddl_ppstatus.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(ddl_ppstatus);
break;
default:
TextBox txt = new TextBox();
txt.Width = new Unit("90%");
txt.Attributes.Add("onkeyup", "TableViewer_Mark_Field_Altered(this);");
txt.Attributes.Add("onfocus", "TableViewer_Set_Field_Defaults(this)");
cell.Controls.Add(txt);
break;
}
}
else if (fieldType == FieldType.LinkButton)
{
LinkButton lbt = new LinkButton();
lbt.CommandName = "Sel";
cell.Controls.Add(lbt);
}
else if (fieldType == FieldType.Delete)
{
this.IsEditing = false;
CheckBox cbx = new CheckBox();
cbx.Attributes.Add("onclick", "if (this.checked) this.parentNode.style.backgroundColor = 'Red'; else this.parentNode.style.backgroundColor = '';");
cell.Controls.Add(cbx);
}
} protected override void OnDataBindField(object sender, EventArgs e)
{
Control control = (Control)sender;
GridViewRow row = control.NamingContainer as GridViewRow;
object dataValue = this.GetValue(control.NamingContainer); if (fieldType == FieldType.Status)
{
if (dataValue != null)
{
switch (dataValue.ToString().ToUpper())
{
case "ACTIVE":
row.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
break;
case "PENDING":
row.BackColor = System.Drawing.ColorTranslator.FromHtml("#FCD5E5");
row.Font.Italic = true;
break;
case "INACTIVE":
row.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFF3CE");
break;
}
}
} if (IsEditing)
{
if (this.fieldType == FieldType.DateTime)
{
//if (dataValue != null)
//{
// if (dataValue.GetType().Name == "DateTime")
// {
// ((DateSelector)control.Controls[0]).DateTime = (DateTime)dataValue;
// }
// else
// {
// try
// {
// ((DateSelector)control.Controls[0]).DateTime = DateTime.Parse(dataValue.ToString());
// }
// catch
// { }
// }
//} }
if (this.fieldType == FieldType.TextBox)
{
if (dataValue != null)
((TextBox)control.Controls[]).Text = dataValue.ToString();
}
if (this.fieldType == FieldType.LinkButton)
{
if (dataValue != null)
((TextBox)control.Controls[]).Text = dataValue.ToString();
}
if (this.fieldType == FieldType.CheckBox)
{
if (dataValue != null)
((CheckBox)control.Controls[]).Checked = (bool)dataValue;
}
if (this.fieldType == FieldType.Int)
{
if (dataValue != null)
((TextBox)control.Controls[]).Text = dataValue.ToString();
}
if (this.fieldType == FieldType.MaxQty)
{
if (dataValue != null)
((TextBox)control.Controls[]).Text = dataValue.ToString();
}
if (this.fieldType == FieldType.Double)
{
if (dataValue != null)
((TextBox)control.Controls[]).Text = dataValue.ToString();
}
if (this.fieldType == FieldType.Status)
{
if (dataValue != null)
{
switch (dataValue.ToString().ToUpper())
{
case "ACTIVE":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
case "PENDING":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
case "INACTIVE":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
}
}
} if (this.fieldType == FieldType.PPStatus)
{
if (dataValue != null)
{
switch (dataValue.ToString().ToUpper())
{
case "ACTIVE":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
case "PENDING":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
case "INACTIVE":
((DropDownList)control.Controls[]).SelectedValue = "";
break;
}
}
} if (this.fieldType == FieldType.Duration)
{
if (dataValue != null)
{ string[] _info = dataValue.ToString().Split(' '); if (_info.Length == )
{ if (!string.IsNullOrEmpty(_info[].ToString()))
{
((TextBox)control.Controls[]).Text = _info[].ToString();
} if (!string.IsNullOrEmpty(_info[].ToString()))
{
((DropDownList)control.Controls[]).SelectedValue = _info[].ToString();
}
} }
} }
else if (control.Controls.Count > && this.fieldType == FieldType.LinkButton)
{
if (dataValue != null)
{
((LinkButton)control.Controls[]).Text = dataValue.ToString();
((LinkButton)control.Controls[]).CommandArgument = ((GridViewRow)control.Parent).RowIndex.ToString();
}
}
else
{
base.OnDataBindField(sender, e);
}
}
} public enum FieldType
{
TextBox,
CheckBox,
Status,
LinkButton,
Delete,
DateTime,
Int,
Double,
Feature,
CheckBoxFeature,
Duration,
MaxQty,
PPStatus,
}
}
ASP.net 自定义控件GridView的更多相关文章
- asp.net教程:GridView导出到Excel或Word文件
asp.net教程:GridView导出到Excel或Word文件</ br> 在项目中我们经常会遇到要求将一些数据导出成Excel或者Word表格的情况,比如中国移动(我是中国移动用户) ...
- asp.net 自定义控件
在Visual Studio中,所有的ASP.NET 2.0控件都是自定义控件,创建自己的自定义控件一般需要完成以下三步.(1)在站点APP_Code下创建一个新类:(2)修改这个类,让它成为WebC ...
- ASP.NET自定义控件组件开发 第五章 模板控件开发
原文:ASP.NET自定义控件组件开发 第五章 模板控件开发 第五章 模板控件开发 系列文章链接: ASP.NET自定义控件组件开发 第一章 待续 ASP.NET自定义控件组件开发 第一章 第二篇 接 ...
- ASP.NET自定义控件组件开发 第四章 组合控件开发CompositeControl
原文:ASP.NET自定义控件组件开发 第四章 组合控件开发CompositeControl 第四章 组合控件开发CompositeControl 大家好,今天我们来实现一个自定义的控件,之前我们已经 ...
- ASP.NET自定义控件组件开发 第四章 组合控件开发CompositeControl 后篇 --事件冒泡
原文:ASP.NET自定义控件组件开发 第四章 组合控件开发CompositeControl 后篇 --事件冒泡 CompositeControl 后篇 --事件冒泡 系列文章链接: ASP.NET ...
- ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇
原文:ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇 第三章 为控件添加事件 好了,我们之前以前开发一个控件.而且也添加了属性,开发也很规范,但是那个控件还差最后一点:添加事件. 系列 ...
- ASP.NET自定义控件组件开发 第三章 为控件添加事件 后篇
原文:ASP.NET自定义控件组件开发 第三章 为控件添加事件 后篇 第三章 为控件添加事件 后篇 前一篇文章只是简单的说了下事件,但是大家应该方法,在ASP.NET自定义控件中只是简单那么定义事件是 ...
- ASP.NET自定义控件组件开发 第一章 第三篇
原文:ASP.NET自定义控件组件开发 第一章 第三篇 第三篇:第一章的完结篇 系列文章链接: ASP.NET自定义控件组件开发 第一章 待续 ASP.NET自定义控件组件开发 第一章 第二篇 接着待 ...
- ASP.NET自定义控件组件开发 第二章 继承WebControl的自定义控件
原文:ASP.NET自定义控件组件开发 第二章 继承WebControl的自定义控件 第二章 继承于WebControl的自定义控件 到现在为止,我已经写了三篇关于自定义控件开发的文章,很感谢大家的支 ...
随机推荐
- CASE WHEN的两种格式
CASE WHEN的两种格式 1.简单Case函数 CASE sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其他' END 2.Case搜索函数 CASE ...
- Webdriver中实现区域截图的方式以及如何截取frame中的图片
import java.awt.Rectangle;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOE ...
- 【转】对于JNI方法名,数据类型和方法签名的一些认识
[转]对于JNI方法名,数据类型和方法签名的一些认识 之前一直用jni,但是没有考虑Java重载函数,如何在jni-C++里命名,今天看到一篇文章,讲到了类型签名. 原文链接:http://www ...
- Android 系统编译
最近研究了下Android 的编译系统,下面结合编译我们自己的产品 mobot 来对整个编译系统进行必要的介绍,方便大家今 后对默认编译的修改. 先列出几个觉得重要的Make 文件: build/bu ...
- Android开发10.2:UI组件AutoCompleteTextView(自动完成文本框)
概述 AutoCompleteTextVeiw(自动完成文本框)从 EditText派生而出 PS :EditText用法介绍 当用户输入一定字符后,自动完成自动完成文本框会显示 ...
- cocos2d-x 那些常犯的错误
Label::_label; if(_label==NULL){ //初始化_label的代码 } //指针默认值不等于NULL,需要赋初始值Label::_label=NULL; string st ...
- InnoDB的数据页结构
页是InnoDB存储引擎管理数据库的最小磁盘单位.页类型为B-tree node的页,存放的即是表中行的实际数据了. InnoDB数据页由以下七个部分组成,如图所示: File Header(文件头) ...
- Disassembly2:Built-in Type
先贴一段代码: 跟踪后看到:
- Chapter 1 First Sight——12
Breakfast with Charlie was a quiet event. 和查理斯吃早饭时一件安静的事情 He wished me good luck at school. I thanke ...
- EXCEL读写NPOI
1.第一步: 可以使用ExcelAutomation进行EXCEl文件的读写,但是需要电脑上安装EXCEL,对EXCEL版本有要求,速度慢,有安全性,并发性问题,不适合网站类项目. 第二种方法: NP ...