HtmlSelect.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. //
  2. // System.Web.UI.HtmlControls.HtmlSelect.cs
  3. //
  4. // Author:
  5. // Dick Porter <[email protected]>
  6. //
  7. // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System.Web.UI.WebControls;
  29. using System.Web.Util;
  30. using System.ComponentModel;
  31. using System.Collections;
  32. using System.Collections.Specialized;
  33. using System.Globalization;
  34. using System.Security.Permissions;
  35. namespace System.Web.UI.HtmlControls
  36. {
  37. // CAS
  38. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. // attributes
  41. [DefaultEvent ("ServerChange")]
  42. [ValidationProperty ("Value")]
  43. [ControlBuilder (typeof (HtmlSelectBuilder))]
  44. [SupportsEventValidation]
  45. public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor
  46. {
  47. static readonly object EventServerChange = new object ();
  48. DataSourceView _boundDataSourceView;
  49. bool requiresDataBinding;
  50. bool _initialized;
  51. object datasource;
  52. ListItemCollection items;
  53. public HtmlSelect () : base ("select")
  54. {
  55. }
  56. [DefaultValue ("")]
  57. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  58. [WebSysDescription("")]
  59. [WebCategory("Data")]
  60. public virtual string DataMember {
  61. get {
  62. string member = Attributes["datamember"];
  63. if (member == null) {
  64. return (String.Empty);
  65. }
  66. return (member);
  67. }
  68. set {
  69. if (value == null) {
  70. Attributes.Remove ("datamember");
  71. } else {
  72. Attributes["datamember"] = value;
  73. }
  74. }
  75. }
  76. [DefaultValue (null)]
  77. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  78. [WebSysDescription("")]
  79. [WebCategory("Data")]
  80. public virtual object DataSource {
  81. get {
  82. return (datasource);
  83. }
  84. set {
  85. if ((value != null) &&
  86. !(value is IEnumerable) &&
  87. !(value is IListSource)) {
  88. throw new ArgumentException ();
  89. }
  90. datasource = value;
  91. }
  92. }
  93. [DefaultValue ("")]
  94. public virtual string DataSourceID {
  95. get {
  96. return ViewState.GetString ("DataSourceID", "");
  97. }
  98. set {
  99. if (DataSourceID == value)
  100. return;
  101. ViewState ["DataSourceID"] = value;
  102. if (_boundDataSourceView != null)
  103. _boundDataSourceView.DataSourceViewChanged -= OnDataSourceViewChanged;
  104. _boundDataSourceView = null;
  105. OnDataPropertyChanged ();
  106. }
  107. }
  108. [DefaultValue ("")]
  109. [WebSysDescription("")]
  110. [WebCategory("Data")]
  111. public virtual string DataTextField {
  112. get {
  113. string text = Attributes["datatextfield"];
  114. if (text == null) {
  115. return (String.Empty);
  116. }
  117. return (text);
  118. }
  119. set {
  120. if (value == null) {
  121. Attributes.Remove ("datatextfield");
  122. } else {
  123. Attributes["datatextfield"] = value;
  124. }
  125. }
  126. }
  127. [DefaultValue ("")]
  128. [WebSysDescription("")]
  129. [WebCategory("Data")]
  130. public virtual string DataValueField {
  131. get {
  132. string value = Attributes["datavaluefield"];
  133. if (value == null) {
  134. return (String.Empty);
  135. }
  136. return (value);
  137. }
  138. set {
  139. if (value == null) {
  140. Attributes.Remove ("datavaluefield");
  141. } else {
  142. Attributes["datavaluefield"] = value;
  143. }
  144. }
  145. }
  146. public override string InnerHtml {
  147. get {
  148. throw new NotSupportedException ();
  149. }
  150. set {
  151. throw new NotSupportedException ();
  152. }
  153. }
  154. public override string InnerText {
  155. get {
  156. throw new NotSupportedException ();
  157. }
  158. set {
  159. throw new NotSupportedException ();
  160. }
  161. }
  162. protected bool IsBoundUsingDataSourceID {
  163. get {
  164. return (DataSourceID.Length != 0);
  165. }
  166. }
  167. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  168. [Browsable (false)]
  169. public ListItemCollection Items {
  170. get {
  171. if (items == null) {
  172. items = new ListItemCollection ();
  173. if (IsTrackingViewState)
  174. ((IStateManager) items).TrackViewState ();
  175. }
  176. return (items);
  177. }
  178. }
  179. [DefaultValue ("")]
  180. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  181. [WebSysDescription("")]
  182. [WebCategory("Behavior")]
  183. public bool Multiple {
  184. get {
  185. string multi = Attributes["multiple"];
  186. if (multi == null) {
  187. return (false);
  188. }
  189. return (true);
  190. }
  191. set {
  192. if (value == false) {
  193. Attributes.Remove ("multiple");
  194. } else {
  195. Attributes["multiple"] = "multiple";
  196. }
  197. }
  198. }
  199. [DefaultValue ("")]
  200. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  201. [WebSysDescription("")]
  202. [WebCategory("Behavior")]
  203. public string Name {
  204. get {
  205. return (UniqueID);
  206. }
  207. set {
  208. /* Do nothing */
  209. }
  210. }
  211. protected bool RequiresDataBinding {
  212. get { return requiresDataBinding; }
  213. set { requiresDataBinding = value; }
  214. }
  215. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  216. [Browsable (false)]
  217. public virtual int SelectedIndex {
  218. get {
  219. /* Make sure Items has been initialised */
  220. ListItemCollection listitems = Items;
  221. for (int i = 0; i < listitems.Count; i++) {
  222. if (listitems[i].Selected) {
  223. return (i);
  224. }
  225. }
  226. /* There is always a selected item in
  227. * non-multiple mode, if the size is
  228. * <= 1
  229. */
  230. if (!Multiple && Size <= 1) {
  231. /* Select the first item */
  232. if (listitems.Count > 0) {
  233. /* And make it stick
  234. * if there is
  235. * anything in the
  236. * list
  237. */
  238. listitems[0].Selected = true;
  239. }
  240. return (0);
  241. }
  242. return (-1);
  243. }
  244. set {
  245. ClearSelection ();
  246. if (value == -1 || items == null) {
  247. return;
  248. }
  249. if (value < 0 || value >= items.Count) {
  250. throw new ArgumentOutOfRangeException ("value");
  251. }
  252. items[value].Selected = true;
  253. }
  254. }
  255. /* "internal infrastructure" according to the docs,
  256. * but has some documentation in 2.0
  257. */
  258. protected virtual int[] SelectedIndices {
  259. get {
  260. ArrayList selected = new ArrayList ();
  261. int count = Items.Count;
  262. for (int i = 0; i < count; i++) {
  263. if (Items [i].Selected) {
  264. selected.Add (i);
  265. }
  266. }
  267. return ((int[])selected.ToArray (typeof (int)));
  268. }
  269. }
  270. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  271. public int Size {
  272. get {
  273. string size = Attributes["size"];
  274. if (size == null) {
  275. return (-1);
  276. }
  277. return (Int32.Parse (size, Helpers.InvariantCulture));
  278. }
  279. set {
  280. if (value == -1) {
  281. Attributes.Remove ("size");
  282. } else {
  283. Attributes["size"] = value.ToString ();
  284. }
  285. }
  286. }
  287. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  288. public string Value {
  289. get {
  290. int sel = SelectedIndex;
  291. if (sel >= 0 && sel < Items.Count) {
  292. return (Items[sel].Value);
  293. }
  294. return (String.Empty);
  295. }
  296. set {
  297. int sel = Items.IndexOf (value);
  298. if (sel >= 0) {
  299. SelectedIndex = sel;
  300. }
  301. }
  302. }
  303. [WebSysDescription("")]
  304. [WebCategory("Action")]
  305. public event EventHandler ServerChange {
  306. add {
  307. Events.AddHandler (EventServerChange, value);
  308. }
  309. remove {
  310. Events.RemoveHandler (EventServerChange, value);
  311. }
  312. }
  313. protected override void AddParsedSubObject (object obj)
  314. {
  315. if (!(obj is ListItem)) {
  316. throw new HttpException ("HtmlSelect can only contain ListItem");
  317. }
  318. Items.Add ((ListItem)obj);
  319. base.AddParsedSubObject (obj);
  320. }
  321. /* "internal infrastructure" according to the docs,
  322. * but has some documentation in 2.0
  323. */
  324. protected virtual void ClearSelection ()
  325. {
  326. if (items == null) {
  327. return;
  328. }
  329. int count = items.Count;
  330. for (int i = 0; i < count; i++) {
  331. items[i].Selected = false;
  332. }
  333. }
  334. protected override ControlCollection CreateControlCollection ()
  335. {
  336. return (base.CreateControlCollection ());
  337. }
  338. protected void EnsureDataBound ()
  339. {
  340. if (IsBoundUsingDataSourceID && RequiresDataBinding)
  341. DataBind ();
  342. }
  343. protected virtual IEnumerable GetData ()
  344. {
  345. if (DataSource != null && IsBoundUsingDataSourceID)
  346. throw new HttpException ("Control bound using both DataSourceID and DataSource properties.");
  347. if (DataSource != null)
  348. return DataSourceResolver.ResolveDataSource (DataSource, DataMember);
  349. if (!IsBoundUsingDataSourceID)
  350. return null;
  351. IEnumerable result = null;
  352. DataSourceView boundDataSourceView = ConnectToDataSource ();
  353. boundDataSourceView.Select (DataSourceSelectArguments.Empty, delegate (IEnumerable data) { result = data; });
  354. return result;
  355. }
  356. protected override void LoadViewState (object savedState)
  357. {
  358. object first = null;
  359. object second = null;
  360. Pair pair = savedState as Pair;
  361. if (pair != null) {
  362. first = pair.First;
  363. second = pair.Second;
  364. }
  365. base.LoadViewState (first);
  366. if (second != null) {
  367. IStateManager manager = Items as IStateManager;
  368. manager.LoadViewState (second);
  369. }
  370. }
  371. protected override void OnDataBinding (EventArgs e)
  372. {
  373. base.OnDataBinding (e);
  374. /* Make sure Items has been initialised */
  375. ListItemCollection listitems = Items;
  376. listitems.Clear ();
  377. IEnumerable list = GetData ();
  378. if (list == null)
  379. return;
  380. foreach (object container in list) {
  381. string text = null;
  382. string value = null;
  383. if (DataTextField == String.Empty &&
  384. DataValueField == String.Empty) {
  385. text = container.ToString ();
  386. value = text;
  387. } else {
  388. if (DataTextField != String.Empty) {
  389. text = DataBinder.Eval (container, DataTextField).ToString ();
  390. }
  391. if (DataValueField != String.Empty) {
  392. value = DataBinder.Eval (container, DataValueField).ToString ();
  393. } else {
  394. value = text;
  395. }
  396. if (text == null &&
  397. value != null) {
  398. text = value;
  399. }
  400. }
  401. if (text == null) {
  402. text = String.Empty;
  403. }
  404. if (value == null) {
  405. value = String.Empty;
  406. }
  407. ListItem item = new ListItem (text, value);
  408. listitems.Add (item);
  409. }
  410. RequiresDataBinding = false;
  411. IsDataBound = true;
  412. }
  413. protected virtual void OnDataPropertyChanged ()
  414. {
  415. if (_initialized)
  416. RequiresDataBinding = true;
  417. }
  418. protected virtual void OnDataSourceViewChanged (object sender,
  419. EventArgs e)
  420. {
  421. RequiresDataBinding = true;
  422. }
  423. protected internal override void OnInit (EventArgs e)
  424. {
  425. base.OnInit (e);
  426. Page.PreLoad += new EventHandler (OnPagePreLoad);
  427. }
  428. protected virtual void OnPagePreLoad (object sender, EventArgs e)
  429. {
  430. Initialize ();
  431. }
  432. protected internal override void OnLoad (EventArgs e)
  433. {
  434. if (!_initialized)
  435. Initialize ();
  436. base.OnLoad (e);
  437. }
  438. void Initialize ()
  439. {
  440. _initialized = true;
  441. if (!IsDataBound)
  442. RequiresDataBinding = true;
  443. if (IsBoundUsingDataSourceID)
  444. ConnectToDataSource ();
  445. }
  446. bool IsDataBound{
  447. get {
  448. return ViewState.GetBool ("_DataBound", false);
  449. }
  450. set {
  451. ViewState ["_DataBound"] = value;
  452. }
  453. }
  454. DataSourceView ConnectToDataSource ()
  455. {
  456. if (_boundDataSourceView != null)
  457. return _boundDataSourceView;
  458. /* verify that the data source exists and is an IDataSource */
  459. object ctrl = null;
  460. Page page = Page;
  461. if (page != null)
  462. ctrl = page.FindControl (DataSourceID);
  463. if (ctrl == null || !(ctrl is IDataSource)) {
  464. string format;
  465. if (ctrl == null)
  466. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found.";
  467. else
  468. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource.";
  469. throw new HttpException (String.Format (format, ID, DataSourceID));
  470. }
  471. _boundDataSourceView = ((IDataSource)ctrl).GetView (String.Empty);
  472. _boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
  473. return _boundDataSourceView;
  474. }
  475. protected internal override void OnPreRender (EventArgs e)
  476. {
  477. EnsureDataBound ();
  478. base.OnPreRender (e);
  479. Page page = Page;
  480. if (page != null && !Disabled) {
  481. page.RegisterRequiresPostBack (this);
  482. page.RegisterEnabledControl (this);
  483. }
  484. }
  485. protected virtual void OnServerChange (EventArgs e)
  486. {
  487. EventHandler handler = (EventHandler)Events[EventServerChange];
  488. if (handler != null) {
  489. handler (this, e);
  490. }
  491. }
  492. protected override void RenderAttributes (HtmlTextWriter w)
  493. {
  494. Page page = Page;
  495. if (page != null)
  496. page.ClientScript.RegisterForEventValidation (UniqueID);
  497. /* If there is no "name" attribute,
  498. * LoadPostData doesn't work...
  499. */
  500. w.WriteAttribute ("name", Name);
  501. Attributes.Remove ("name");
  502. /* Don't render the databinding attributes */
  503. Attributes.Remove ("datamember");
  504. Attributes.Remove ("datatextfield");
  505. Attributes.Remove ("datavaluefield");
  506. base.RenderAttributes (w);
  507. }
  508. protected internal override void RenderChildren (HtmlTextWriter w)
  509. {
  510. base.RenderChildren (w);
  511. if (items == null)
  512. return;
  513. w.WriteLine ();
  514. bool done_sel = false;
  515. int count = items.Count;
  516. for (int i = 0; i < count; i++) {
  517. ListItem item = items[i];
  518. w.Indent++;
  519. /* Write the <option> elements this
  520. * way so that the output HTML matches
  521. * the ms version (can't make
  522. * HtmlTextWriterTag.Option an inline
  523. * element, cos that breaks other
  524. * stuff.)
  525. */
  526. w.WriteBeginTag ("option");
  527. if (item.Selected && !done_sel) {
  528. w.WriteAttribute ("selected", "selected");
  529. if (!Multiple) {
  530. done_sel = true;
  531. }
  532. }
  533. w.WriteAttribute ("value", item.Value, true);
  534. w.Write (HtmlTextWriter.TagRightChar);
  535. w.Write (HttpUtility.HtmlEncode(item.Text));
  536. w.WriteEndTag ("option");
  537. w.WriteLine ();
  538. w.Indent--;
  539. }
  540. }
  541. protected override object SaveViewState ()
  542. {
  543. object first = null;
  544. object second = null;
  545. first = base.SaveViewState ();
  546. IStateManager manager = items as IStateManager;
  547. if (manager != null) {
  548. second = manager.SaveViewState ();
  549. }
  550. if (first == null && second == null)
  551. return (null);
  552. return new Pair (first, second);
  553. }
  554. /* "internal infrastructure" according to the docs,
  555. * but has some documentation in 2.0
  556. */
  557. protected virtual void Select (int[] selectedIndices)
  558. {
  559. if (items == null) {
  560. return;
  561. }
  562. ClearSelection ();
  563. int count = items.Count;
  564. foreach (int i in selectedIndices) {
  565. if (i >= 0 && i < count) {
  566. items[i].Selected = true;
  567. }
  568. }
  569. }
  570. protected override void TrackViewState ()
  571. {
  572. base.TrackViewState ();
  573. IStateManager manager = items as IStateManager;
  574. if (manager != null) {
  575. manager.TrackViewState ();
  576. }
  577. }
  578. protected virtual void RaisePostDataChangedEvent ()
  579. {
  580. OnServerChange (EventArgs.Empty);
  581. }
  582. protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
  583. {
  584. /* postCollection contains the values that are
  585. * selected
  586. */
  587. string[] values = postCollection.GetValues (postDataKey);
  588. bool changed = false;
  589. if (values != null) {
  590. if (Multiple) {
  591. /* We have a set of
  592. * selections. We can't just
  593. * set the new list, because
  594. * we need to know if the set
  595. * has changed from last time
  596. */
  597. int value_len = values.Length;
  598. int[] old_sel = SelectedIndices;
  599. int[] new_sel = new int[value_len];
  600. int old_sel_len = old_sel.Length;
  601. for (int i = 0; i < value_len; i++) {
  602. new_sel[i] = Items.IndexOf (values[i]);
  603. if (old_sel_len != value_len ||
  604. old_sel[i] != new_sel[i]) {
  605. changed = true;
  606. }
  607. }
  608. if (changed) {
  609. Select (new_sel);
  610. }
  611. } else {
  612. /* Just take the first one */
  613. int sel = Items.IndexOf (values[0]);
  614. if (sel != SelectedIndex) {
  615. SelectedIndex = sel;
  616. changed = true;
  617. }
  618. }
  619. }
  620. if (changed)
  621. ValidateEvent (postDataKey, String.Empty);
  622. return (changed);
  623. }
  624. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
  625. {
  626. return LoadPostData (postDataKey, postCollection);
  627. }
  628. void IPostBackDataHandler.RaisePostDataChangedEvent ()
  629. {
  630. RaisePostDataChangedEvent ();
  631. }
  632. }
  633. }