HtmlSelect.cs 17 KB

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