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. #if NET_2_0
  45. [SupportsEventValidation]
  46. public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor {
  47. DataSourceView boundDataSourceView;
  48. IDataSource boundDataSource;
  49. private bool requiresDataBinding;
  50. IEnumerable data;
  51. #else
  52. public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler {
  53. #endif
  54. public HtmlSelect () : base ("select")
  55. {
  56. }
  57. [DefaultValue ("")]
  58. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  59. [WebSysDescription("")]
  60. [WebCategory("Data")]
  61. public virtual string DataMember
  62. {
  63. get {
  64. string member = Attributes["datamember"];
  65. if (member == null) {
  66. return (String.Empty);
  67. }
  68. return (member);
  69. }
  70. set {
  71. if (value == null) {
  72. Attributes.Remove ("datamember");
  73. } else {
  74. Attributes["datamember"] = value;
  75. }
  76. }
  77. }
  78. object datasource;
  79. [DefaultValue (null)]
  80. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  81. [WebSysDescription("")]
  82. [WebCategory("Data")]
  83. public virtual object DataSource
  84. {
  85. get {
  86. return (datasource);
  87. }
  88. set {
  89. if ((value != null) &&
  90. !(value is IEnumerable) &&
  91. !(value is IListSource)) {
  92. throw new ArgumentException ();
  93. }
  94. datasource = value;
  95. }
  96. }
  97. #if NET_2_0
  98. [DefaultValue ("")]
  99. public virtual string DataSourceID
  100. {
  101. get {
  102. return ViewState.GetString ("DataSourceID", "");
  103. }
  104. set {
  105. if (datasource != null)
  106. throw new HttpException ("Only one of DataSource and DataSourceID can be specified.");
  107. ViewState ["DataSourceID"] = value;
  108. OnDataPropertyChanged ();
  109. }
  110. }
  111. #endif
  112. [DefaultValue ("")]
  113. [WebSysDescription("")]
  114. [WebCategory("Data")]
  115. public virtual string DataTextField
  116. {
  117. get {
  118. string text = Attributes["datatextfield"];
  119. if (text == null) {
  120. return (String.Empty);
  121. }
  122. return (text);
  123. }
  124. set {
  125. if (value == null) {
  126. Attributes.Remove ("datatextfield");
  127. } else {
  128. Attributes["datatextfield"] = value;
  129. }
  130. }
  131. }
  132. [DefaultValue ("")]
  133. [WebSysDescription("")]
  134. [WebCategory("Data")]
  135. public virtual string DataValueField
  136. {
  137. get {
  138. string value = Attributes["datavaluefield"];
  139. if (value == null) {
  140. return (String.Empty);
  141. }
  142. return (value);
  143. }
  144. set {
  145. if (value == null) {
  146. Attributes.Remove ("datavaluefield");
  147. } else {
  148. Attributes["datavaluefield"] = value;
  149. }
  150. }
  151. }
  152. public override string InnerHtml
  153. {
  154. get {
  155. throw new NotSupportedException ();
  156. }
  157. set {
  158. throw new NotSupportedException ();
  159. }
  160. }
  161. public override string InnerText
  162. {
  163. get {
  164. throw new NotSupportedException ();
  165. }
  166. set {
  167. throw new NotSupportedException ();
  168. }
  169. }
  170. #if NET_2_0
  171. protected bool IsBoundUsingDataSourceID
  172. {
  173. get {
  174. return (DataSourceID.Length != 0);
  175. }
  176. }
  177. #endif
  178. ListItemCollection items;
  179. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  180. [Browsable (false)]
  181. public ListItemCollection Items
  182. {
  183. get {
  184. if (items == null) {
  185. items = new ListItemCollection ();
  186. }
  187. return (items);
  188. }
  189. }
  190. [DefaultValue ("")]
  191. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  192. [WebSysDescription("")]
  193. [WebCategory("Behavior")]
  194. public bool Multiple
  195. {
  196. get {
  197. string multi = Attributes["multiple"];
  198. if (multi == null) {
  199. return (false);
  200. }
  201. return (true);
  202. }
  203. set {
  204. if (value == false) {
  205. Attributes.Remove ("multiple");
  206. } else {
  207. Attributes["multiple"] = "multiple";
  208. }
  209. }
  210. }
  211. [DefaultValue ("")]
  212. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  213. [WebSysDescription("")]
  214. [WebCategory("Behavior")]
  215. public string Name
  216. {
  217. get {
  218. return (UniqueID);
  219. }
  220. set {
  221. /* Do nothing */
  222. }
  223. }
  224. #if NET_2_0
  225. protected bool RequiresDataBinding
  226. {
  227. get { return requiresDataBinding; }
  228. set { requiresDataBinding = value; }
  229. }
  230. #endif
  231. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  232. [Browsable (false)]
  233. public virtual int SelectedIndex
  234. {
  235. get {
  236. /* Make sure Items has been initialised */
  237. ListItemCollection listitems = Items;
  238. for (int i = 0; i < listitems.Count; i++) {
  239. if (listitems[i].Selected) {
  240. return (i);
  241. }
  242. }
  243. /* There is always a selected item in
  244. * non-multiple mode, if the size is
  245. * <= 1
  246. */
  247. if (!Multiple && Size <= 1) {
  248. /* Select the first item */
  249. if (listitems.Count > 0) {
  250. /* And make it stick
  251. * if there is
  252. * anything in the
  253. * list
  254. */
  255. listitems[0].Selected = true;
  256. }
  257. return (0);
  258. }
  259. return (-1);
  260. }
  261. set {
  262. ClearSelection ();
  263. if (value == -1 || items == null) {
  264. return;
  265. }
  266. if (value < 0 || value >= items.Count) {
  267. throw new ArgumentOutOfRangeException ("value");
  268. }
  269. items[value].Selected = true;
  270. }
  271. }
  272. /* "internal infrastructure" according to the docs,
  273. * but has some documentation in 2.0
  274. */
  275. protected virtual int[] SelectedIndices
  276. {
  277. get {
  278. ArrayList selected = new ArrayList ();
  279. int count = Items.Count;
  280. for (int i = 0; i < count; i++) {
  281. if (Items [i].Selected) {
  282. selected.Add (i);
  283. }
  284. }
  285. return ((int[])selected.ToArray (typeof (int)));
  286. }
  287. }
  288. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  289. public int Size
  290. {
  291. get {
  292. string size = Attributes["size"];
  293. if (size == null) {
  294. return (-1);
  295. }
  296. return (Int32.Parse (size, CultureInfo.InvariantCulture));
  297. }
  298. set {
  299. if (value == -1) {
  300. Attributes.Remove ("size");
  301. } else {
  302. Attributes["size"] = value.ToString ();
  303. }
  304. }
  305. }
  306. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  307. public string Value
  308. {
  309. get {
  310. int sel = SelectedIndex;
  311. if (sel >= 0 && sel < Items.Count) {
  312. return (Items[sel].Value);
  313. }
  314. return (String.Empty);
  315. }
  316. set {
  317. int sel = Items.IndexOf (value);
  318. if (sel >= 0) {
  319. SelectedIndex = sel;
  320. }
  321. }
  322. }
  323. private static readonly object EventServerChange = new object ();
  324. [WebSysDescription("")]
  325. [WebCategory("Action")]
  326. public event EventHandler ServerChange
  327. {
  328. add {
  329. Events.AddHandler (EventServerChange, value);
  330. }
  331. remove {
  332. Events.RemoveHandler (EventServerChange, value);
  333. }
  334. }
  335. protected override void AddParsedSubObject (object obj)
  336. {
  337. if (!(obj is ListItem)) {
  338. throw new HttpException ("HtmlSelect can only contain ListItem");
  339. }
  340. Items.Add ((ListItem)obj);
  341. base.AddParsedSubObject (obj);
  342. }
  343. /* "internal infrastructure" according to the docs,
  344. * but has some documentation in 2.0
  345. */
  346. protected virtual void ClearSelection ()
  347. {
  348. if (items == null) {
  349. return;
  350. }
  351. int count = items.Count;
  352. for (int i = 0; i < count; i++) {
  353. items[i].Selected = false;
  354. }
  355. }
  356. protected override ControlCollection CreateControlCollection ()
  357. {
  358. return (base.CreateControlCollection ());
  359. }
  360. #if NET_2_0
  361. protected void EnsureDataBound ()
  362. {
  363. if (IsBoundUsingDataSourceID && RequiresDataBinding)
  364. DataBind ();
  365. }
  366. private void SelectCallback (IEnumerable data)
  367. {
  368. this.data = data;
  369. }
  370. protected virtual IEnumerable GetData ()
  371. {
  372. IEnumerable result;
  373. if (DataSourceID.Length == 0)
  374. return null;
  375. boundDataSourceView = boundDataSource.GetView (String.Empty);
  376. boundDataSourceView.Select (new DataSourceSelectArguments (), SelectCallback);
  377. boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
  378. result = data;
  379. data = null;
  380. return result;
  381. }
  382. #endif
  383. protected override void LoadViewState (object savedState)
  384. {
  385. object first = null;
  386. object second = null;
  387. int[] selected = null;
  388. Triplet triplet = savedState as Triplet;
  389. if (triplet != null) {
  390. first = triplet.First;
  391. second = triplet.Second;
  392. selected = triplet.Third as int[];
  393. }
  394. base.LoadViewState (first);
  395. if (second != null) {
  396. IStateManager manager = Items as IStateManager;
  397. manager.LoadViewState (second);
  398. }
  399. if (selected != null) {
  400. Select (selected);
  401. }
  402. }
  403. protected override void OnDataBinding (EventArgs e)
  404. {
  405. base.OnDataBinding (e);
  406. /* Make sure Items has been initialised */
  407. ListItemCollection listitems = Items;
  408. listitems.Clear ();
  409. IEnumerable list;
  410. #if NET_2_0
  411. if (IsBoundUsingDataSourceID)
  412. list = GetData ();
  413. else
  414. #endif
  415. list = DataSourceResolver.ResolveDataSource (DataSource, DataMember);
  416. if (list == null) {
  417. return;
  418. }
  419. foreach (object container in list) {
  420. string text = null;
  421. string value = null;
  422. if (DataTextField == String.Empty &&
  423. DataValueField == String.Empty) {
  424. text = container.ToString ();
  425. value = text;
  426. } else {
  427. if (DataTextField != String.Empty) {
  428. text = DataBinder.Eval (container, DataTextField).ToString ();
  429. }
  430. if (DataValueField != String.Empty) {
  431. value = DataBinder.Eval (container, DataValueField).ToString ();
  432. } else {
  433. value = text;
  434. }
  435. if (text == null &&
  436. value != null) {
  437. text = value;
  438. }
  439. }
  440. if (text == null) {
  441. text = String.Empty;
  442. }
  443. if (value == null) {
  444. value = String.Empty;
  445. }
  446. ListItem item = new ListItem (text, value);
  447. listitems.Add (item);
  448. }
  449. }
  450. #if NET_2_0
  451. protected virtual void OnDataPropertyChanged ()
  452. {
  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. }
  464. protected internal override void OnLoad (EventArgs e)
  465. {
  466. if ((Page != null) && !Page.IsPostBack)
  467. RequiresDataBinding = true;
  468. base.OnLoad (e);
  469. if (IsBoundUsingDataSourceID)
  470. ConnectToDataSource ();
  471. }
  472. void ConnectToDataSource ()
  473. {
  474. /* verify that the data source exists and is an IDataSource */
  475. object ctrl = null;
  476. if (Page != null)
  477. ctrl = Page.FindControl (DataSourceID);
  478. if (ctrl == null || !(ctrl is IDataSource)) {
  479. string format;
  480. if (ctrl == null)
  481. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found.";
  482. else
  483. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource.";
  484. throw new HttpException (String.Format (format, ID, DataSourceID));
  485. }
  486. boundDataSource = (IDataSource)ctrl;
  487. }
  488. #endif
  489. #if NET_2_0
  490. protected internal
  491. #else
  492. protected
  493. #endif
  494. override void OnPreRender (EventArgs e)
  495. {
  496. #if NET_2_0
  497. EnsureDataBound ();
  498. #endif
  499. base.OnPreRender (e);
  500. if (Page != null) {
  501. Page.RegisterRequiresPostBack (this);
  502. }
  503. }
  504. protected virtual void OnServerChange (EventArgs e)
  505. {
  506. EventHandler handler = (EventHandler)Events[EventServerChange];
  507. if (handler != null) {
  508. handler (this, e);
  509. }
  510. }
  511. protected override void RenderAttributes (HtmlTextWriter w)
  512. {
  513. #if NET_2_0
  514. if (Page != null)
  515. Page.ClientScript.RegisterForEventValidation (this.UniqueID);
  516. #endif
  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. }