DataPager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // System.Web.UI.WebControls.DataPager
  3. //
  4. // Authors:
  5. // Marek Habersack ([email protected])
  6. //
  7. // (C) 2007 Novell, Inc
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_3_5
  30. using System;
  31. using System.ComponentModel;
  32. using System.Security.Permissions;
  33. using System.Web;
  34. using System.Web.UI;
  35. namespace System.Web.UI.WebControls
  36. {
  37. [ThemeableAttribute(true)]
  38. [AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. [AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. public class DataPager : Control, IAttributeAccessor, INamingContainer, ICompositeControlDesignerAccessor
  41. {
  42. const int NO_PAGEABLE_ITEM_CONTAINER = 0;
  43. const int NO_DATABOUND_CONTROL = 1;
  44. const int NO_PAGED_CONTAINER_ID = 2;
  45. const int CONTROL_NOT_PAGEABLE = 3;
  46. const int NO_NAMING_CONTAINER = 4;
  47. const int STATE_BASE_STATE = 0;
  48. const int STATE_TOTAL_ROW_COUNT = 1;
  49. const int STATE_MAXIMUM_ROWS = 2;
  50. const int STATE_START_ROW_INDEX = 3;
  51. string[] _exceptionMessages = {
  52. "No IPageableItemContainer was found. Verify that either the DataPager is inside an IPageableItemContainer or PagedControlID is set to the control ID of an IPageableItemContainer",
  53. "There is no data-bound control associated with the DataPager control.",
  54. "Control with id '{0}' cannot be found in the page",
  55. "Control '{0}' is not pageable",
  56. "DataPager has no naming container"
  57. };
  58. IPageableItemContainer _pageableContainer;
  59. DataPagerFieldCollection _fields;
  60. AttributeCollection _attributes;
  61. int _totalRowCount;
  62. int _startRowIndex;
  63. int _maximumRows = 10;
  64. bool _initDone;
  65. bool _needNewContainerSetup = true;
  66. bool _createPagerFieldsRunning;
  67. public DataPager()
  68. {
  69. _fields = new DataPagerFieldCollection (this);
  70. }
  71. protected virtual void AddAttributesToRender (HtmlTextWriter writer)
  72. {
  73. if (ID != null)
  74. writer.AddAttribute (HtmlTextWriterAttribute.Id, ID);
  75. if (_attributes != null && _attributes.Count > 0) {
  76. foreach (string attr in _attributes.Keys)
  77. writer.AddAttribute (attr, _attributes [attr]);
  78. }
  79. }
  80. protected virtual void ConnectToEvents (IPageableItemContainer container)
  81. {
  82. if (container == null)
  83. throw new ArgumentNullException ("container");
  84. container.TotalRowCountAvailable += new EventHandler <PageEventArgs> (OnTotalRowCountAvailable);
  85. }
  86. protected virtual void CreatePagerFields ()
  87. {
  88. // In theory (on multi-core or SMP machines), OnTotalRowCountAvailable may
  89. // be called asynchronously to this method (since it is a delegate reacting
  90. // to event in the container), so we want to protect ourselves from data
  91. // corruption here. Lock would be an overkill, since we really want to
  92. // create the list only once anyway.
  93. _createPagerFieldsRunning = true;
  94. ControlCollection controls = Controls;
  95. controls.Clear ();
  96. DataPagerFieldItem control;
  97. foreach (DataPagerField dpf in _fields) {
  98. control = new DataPagerFieldItem (dpf, this);
  99. if (dpf.Visible) {
  100. dpf.CreateDataPagers (control, _startRowIndex, _maximumRows, _totalRowCount, _fields.IndexOf (dpf));
  101. control.DataBind ();
  102. }
  103. controls.Add (control);
  104. }
  105. _createPagerFieldsRunning = false;
  106. }
  107. public override void DataBind()
  108. {
  109. OnDataBinding (EventArgs.Empty);
  110. EnsureChildControls ();
  111. DataBindChildren ();
  112. }
  113. protected virtual IPageableItemContainer FindPageableItemContainer ()
  114. {
  115. string pagedControlID = PagedControlID;
  116. IPageableItemContainer ret = null;
  117. if (!String.IsNullOrEmpty (pagedControlID)) {
  118. Control ctl = FindControl (pagedControlID, 0);
  119. if (ret == null)
  120. throw new InvalidOperationException (String.Format (_exceptionMessages [NO_PAGED_CONTAINER_ID], pagedControlID));
  121. ret = ctl as IPageableItemContainer;
  122. if (ret == null)
  123. throw new InvalidOperationException (String.Format (_exceptionMessages [CONTROL_NOT_PAGEABLE], pagedControlID));
  124. return ret;
  125. }
  126. // No ID set, try to find a container that's pageable
  127. Control container = NamingContainer;
  128. Page page = Page;
  129. while (container != page) {
  130. if (container == null)
  131. throw new InvalidOperationException (_exceptionMessages [NO_NAMING_CONTAINER]);
  132. ret = container as IPageableItemContainer;
  133. if (ret != null)
  134. return ret;
  135. container = container.NamingContainer;
  136. }
  137. return ret;
  138. }
  139. protected internal override void LoadControlState (object savedState)
  140. {
  141. object[] state = savedState as object[];
  142. object tmp;
  143. if (state != null) {
  144. base.LoadControlState (state [STATE_BASE_STATE]);
  145. if ((tmp = state [STATE_TOTAL_ROW_COUNT]) != null)
  146. _totalRowCount = (int) tmp;
  147. if ((tmp = state [STATE_MAXIMUM_ROWS]) != null)
  148. _maximumRows = (int) tmp;
  149. if ((tmp = state [STATE_START_ROW_INDEX]) != null)
  150. _startRowIndex = (int) tmp;
  151. }
  152. if (_pageableContainer == null) {
  153. _pageableContainer = FindPageableItemContainer ();
  154. if (_pageableContainer == null)
  155. throw new InvalidOperationException (_exceptionMessages [NO_DATABOUND_CONTROL]);
  156. ConnectToEvents (_pageableContainer);
  157. }
  158. SetUpForNewContainer (false);
  159. }
  160. protected override void LoadViewState (object savedState)
  161. {
  162. Pair state = savedState as Pair;
  163. if (state == null)
  164. return;
  165. base.LoadViewState (state.First);
  166. object myState = state.Second;
  167. if (myState != null)
  168. ((IStateManager) Fields).LoadViewState (myState);
  169. }
  170. protected override bool OnBubbleEvent (object source, EventArgs e)
  171. {
  172. DataPagerFieldCommandEventArgs args = e as DataPagerFieldCommandEventArgs;
  173. if (args != null) {
  174. DataPagerFieldItem item = args.Item;
  175. DataPagerField field = item != null ? item.PagerField : null;
  176. if (field != null) {
  177. field.HandleEvent (args);
  178. return true;
  179. }
  180. }
  181. return false;
  182. }
  183. void SetUpForNewContainer (bool dataBind)
  184. {
  185. if (!_needNewContainerSetup)
  186. return;
  187. ConnectToEvents (_pageableContainer);
  188. _pageableContainer.SetPageProperties (_startRowIndex, _maximumRows, false);
  189. _needNewContainerSetup = false;
  190. }
  191. protected internal override void OnInit (EventArgs e)
  192. {
  193. base.OnInit (e);
  194. Page page = Page;
  195. if (page != null)
  196. page.RegisterRequiresControlState (this);
  197. // It might return null here - there is no guarantee all the controls on the
  198. // page are already initialized by the time this method is loaded. Do not
  199. // throw for that reason.
  200. _pageableContainer = FindPageableItemContainer ();
  201. if (_pageableContainer != null)
  202. // Do not re-bind the data here - not all the controls might be
  203. // initialized (that includes the container may be bound to)
  204. SetUpForNewContainer (false);
  205. _initDone = true;
  206. }
  207. protected internal override void OnLoad (EventArgs e)
  208. {
  209. if (_pageableContainer == null)
  210. _pageableContainer = FindPageableItemContainer ();
  211. if (_pageableContainer == null)
  212. throw new InvalidOperationException (_exceptionMessages [NO_PAGEABLE_ITEM_CONTAINER]);
  213. SetUpForNewContainer (false);
  214. base.OnLoad (e);
  215. }
  216. protected virtual void OnTotalRowCountAvailable (object sender, PageEventArgs e)
  217. {
  218. _totalRowCount = e.TotalRowCount;
  219. _maximumRows = e.MaximumRows;
  220. _startRowIndex = e.StartRowIndex;
  221. // Sanity checks: if the total row count is less than the current start row
  222. // index, we must adjust and rebind the associated container control
  223. if (_totalRowCount > 0 && (_totalRowCount <= _startRowIndex)) {
  224. // Adjust the container's start row index to the new maximum rows
  225. // count, but do not touch our index - we aren't a "view", so we
  226. // don't want/need to change the start index.
  227. int tmp = _startRowIndex - _maximumRows;
  228. if (tmp < 0 || tmp >= _totalRowCount)
  229. tmp = 0;
  230. // Trigger the databinding, which will call us again, with adjusted
  231. // data, so that we can recreate the pager fields.
  232. _pageableContainer.SetPageProperties (tmp, _maximumRows, true);
  233. } else if (!_createPagerFieldsRunning)
  234. // No adjustments necessary, re-create the pager fields
  235. CreatePagerFields ();
  236. }
  237. protected virtual void RecreateChildControls ()
  238. {
  239. // This is used only by VS designer
  240. throw new NotImplementedException ();
  241. }
  242. protected internal override void Render (HtmlTextWriter writer)
  243. {
  244. RenderBeginTag (writer);
  245. RenderContents (writer);
  246. writer.RenderEndTag ();
  247. }
  248. public virtual void RenderBeginTag (HtmlTextWriter writer)
  249. {
  250. AddAttributesToRender (writer);
  251. writer.RenderBeginTag (TagKey);
  252. }
  253. protected virtual void RenderContents (HtmlTextWriter writer)
  254. {
  255. // Nothing special to render, just child controls
  256. base.Render (writer);
  257. }
  258. protected internal override object SaveControlState ()
  259. {
  260. object[] ret = new object [4];
  261. ret [STATE_BASE_STATE] = base.SaveControlState ();
  262. ret [STATE_TOTAL_ROW_COUNT] = _totalRowCount <= 0 ? 0 : _totalRowCount;
  263. ret [STATE_MAXIMUM_ROWS] = _maximumRows <= 0 ? 0 : _maximumRows;
  264. ret [STATE_START_ROW_INDEX] = _startRowIndex <= 0 ? 0 : _startRowIndex;
  265. return ret;
  266. }
  267. protected override object SaveViewState ()
  268. {
  269. Pair ret = new Pair ();
  270. ret.First = base.SaveViewState ();
  271. ret.Second = _fields != null ? ((IStateManager) _fields).SaveViewState () : null;
  272. return ret;
  273. }
  274. public virtual void SetPageProperties (int startRowIndex, int maximumRows, bool databind)
  275. {
  276. if (_pageableContainer == null)
  277. throw new InvalidOperationException (_exceptionMessages [NO_DATABOUND_CONTROL]);
  278. _startRowIndex = startRowIndex;
  279. _maximumRows = maximumRows;
  280. _pageableContainer.SetPageProperties (startRowIndex, maximumRows, databind);
  281. }
  282. protected override void TrackViewState ()
  283. {
  284. base.TrackViewState ();
  285. if (_fields != null)
  286. ((IStateManager) _fields).TrackViewState ();
  287. }
  288. [BrowsableAttribute(false)]
  289. public AttributeCollection Attributes {
  290. get {
  291. if (_attributes == null)
  292. _attributes = new AttributeCollection (new StateBag ());
  293. return _attributes;
  294. }
  295. }
  296. public override ControlCollection Controls {
  297. get {
  298. EnsureChildControls ();
  299. return base.Controls;
  300. }
  301. }
  302. [PersistenceModeAttribute(PersistenceMode.InnerProperty)]
  303. public virtual DataPagerFieldCollection Fields {
  304. get { return _fields; }
  305. }
  306. [BrowsableAttribute(false)]
  307. public int MaximumRows {
  308. get { return _maximumRows; }
  309. }
  310. [ThemeableAttribute(false)]
  311. public virtual string PagedControlID {
  312. get {
  313. string ret = ViewState ["PagedControlID"] as string;
  314. if (ret == null)
  315. return String.Empty;
  316. return ret;
  317. }
  318. set { ViewState ["PagedControlID"] = value; }
  319. }
  320. public int PageSize {
  321. get { return _maximumRows; }
  322. set {
  323. if (value < 1)
  324. throw new ArgumentOutOfRangeException ("value");
  325. if (value == _maximumRows)
  326. return;
  327. _maximumRows = value;
  328. if (_initDone) {
  329. // We have a source and the page size has changed, update
  330. // the container
  331. CreatePagerFields ();
  332. // Environment has changed, let the container know that it
  333. // needs to rebind.
  334. SetPageProperties (_startRowIndex, _maximumRows, true);
  335. }
  336. }
  337. }
  338. public string QueryStringField {
  339. get {
  340. string ret = ViewState ["QueryStringField"] as string;
  341. if (ret == null)
  342. return String.Empty;
  343. return ret;
  344. }
  345. set { ViewState ["QueryStringField"] = value; }
  346. }
  347. [BrowsableAttribute(false)]
  348. public int StartRowIndex {
  349. get { return _startRowIndex; }
  350. }
  351. [BrowsableAttribute(false)]
  352. protected virtual HtmlTextWriterTag TagKey {
  353. get { return HtmlTextWriterTag.Span; }
  354. }
  355. [BrowsableAttribute(false)]
  356. public int TotalRowCount {
  357. get { return _totalRowCount; }
  358. }
  359. string IAttributeAccessor.GetAttribute (string key)
  360. {
  361. return Attributes [key];
  362. }
  363. void IAttributeAccessor.SetAttribute (string key, string value)
  364. {
  365. Attributes [key] = value;
  366. }
  367. void ICompositeControlDesignerAccessor.RecreateChildControls ()
  368. {
  369. RecreateChildControls ();
  370. }
  371. }
  372. }
  373. #endif