HtmlSelect.cs 17 KB

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