/Docs/07-Implementacion/Source/trunk/EDUAR_actual/EDUAR/EDUAR_UI/Utilidades/UIUtilidades.cs

http://blpm.googlecode.com/ · C# · 727 lines · 445 code · 79 blank · 203 comment · 43 complexity · 031c7bed0713e0f74cc3f6f2475d3c0e MD5 · raw file

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Web;
  9. using System.Web.UI;
  10. using System.Web.UI.WebControls;
  11. using EDUAR_Utility.Enumeraciones;
  12. namespace EDUAR_UI.Utilidades
  13. {
  14. public class UIUtilidades
  15. {
  16. /// <summary>
  17. /// Binds the combo tipo persona.
  18. /// </summary>
  19. /// <param name="ddlTipoUsuario">The DDL tipo usuario.</param>
  20. public static void BindComboTipoPersona(DropDownList ddlTipoUsuario)
  21. {
  22. foreach (enumTipoPersona tipoPersona in Enum.GetValues(typeof(enumTipoPersona)))
  23. {
  24. ddlTipoUsuario.Items.Add(new ListItem(tipoPersona.ToString(), ((int)tipoPersona).ToString()));
  25. }
  26. ddlTipoUsuario.Items.Insert(0, new ListItem("Todos", "-1"));
  27. }
  28. //public static void BindRespuestaCuantitativa(RadioButtonList rdlUsuario)
  29. //{
  30. // foreach (enumRespCuantitativa tipoRespuesta in Enum.GetValues(typeof(enumRespCuantitativa)))
  31. // {
  32. // if (((int)tipoRespuesta) > 0)
  33. // rdlUsuario.Items.Add(new ListItem(tipoRespuesta.ToString().Replace("_", " "), ((int)tipoRespuesta).ToString()));
  34. // }
  35. //}
  36. //public static void BindRespuestaCualitativa(RadioButtonList rdlUsuario)
  37. //{
  38. // foreach (enumRespCualitativa tipoRespuesta in Enum.GetValues(typeof(enumRespCualitativa)))
  39. // {
  40. // if (((int)tipoRespuesta) > 0)
  41. // rdlUsuario.Items.Add(new ListItem(tipoRespuesta.ToString().Replace("_", " "), ((int)tipoRespuesta).ToString()));
  42. // }
  43. //}
  44. /// <summary>
  45. /// Binds the combo meses.
  46. /// </summary>
  47. /// <param name="ddlEntidad">The DDL entidad.</param>
  48. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  49. public static void BindComboMeses(DropDownList ddlEntidad, bool addDefaultValue, int startMonth)
  50. {
  51. ddlEntidad.Items.Clear();
  52. foreach (enumMeses mes in Enum.GetValues(typeof(enumMeses)))
  53. {
  54. if ((int)mes > 2 && (int)mes >= startMonth)
  55. ddlEntidad.Items.Add(new ListItem(mes.ToString(), ((int)mes).ToString()));
  56. }
  57. if (addDefaultValue)
  58. ddlEntidad.Items.Insert(0, new ListItem("Todos", "-1"));
  59. }
  60. /// <summary>
  61. /// Método que realiza el Bind de un ListBox.
  62. /// </summary>
  63. /// <typeparam name="T"></typeparam>
  64. /// <param name="ListBox">The list box.</param>
  65. /// <param name="lista">The lista.</param>
  66. /// <param name="fieldId">The field id.</param>
  67. /// <param name="fieldDescription">The field description.</param>
  68. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  69. public static void BindCombo<T>(ListBox ListBox, IList<T> lista, string fieldId, string fieldDescription, bool addDefaultValue)
  70. {
  71. DataView dataView = new DataView((DataTable)lista);
  72. ListBox.Items.Clear();
  73. ListBox.DataSource = null;
  74. if (dataView != null)
  75. {
  76. foreach (DataRowView drv in dataView)
  77. ListBox.Items.Insert(ListBox.Items.Count, new ListItem(drv.Row[fieldDescription].ToString(), drv.Row[fieldId].ToString()));
  78. }
  79. if (addDefaultValue)
  80. ListBox.Items.Insert(0, new ListItem("[Seleccione]", "-1"));
  81. }
  82. /// <summary>
  83. /// Método que realiza el Bind de un DropDownList.
  84. /// </summary>
  85. /// <typeparam name="T"></typeparam>
  86. /// <param name="dropDownList">The drop down list.</param>
  87. /// <param name="lista">The lista.</param>
  88. /// <param name="fieldId">The field id.</param>
  89. /// <param name="fieldDescription">The field description.</param>
  90. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  91. public static void BindCombo<T>(DropDownList dropDownList, IList<T> lista, string fieldId, string fieldDescription, bool addDefaultValue, bool addAllValue, string campoAnterior)
  92. {
  93. DataView dataView = new DataView(BuildDataTable(lista));
  94. dropDownList.Items.Clear();
  95. dropDownList.DataSource = null;
  96. if (dataView != null)
  97. {
  98. foreach (DataRowView drv in dataView)
  99. dropDownList.Items.Insert(dropDownList.Items.Count, new ListItem(drv.Row[fieldDescription].ToString(), drv.Row[fieldId].ToString()));
  100. }
  101. SortByText(dropDownList);
  102. if (addAllValue)
  103. {
  104. dropDownList.Items.Insert(0, new ListItem("[Todos]", "-2"));
  105. dropDownList.SelectedValue = "-2";
  106. }
  107. if (addDefaultValue)
  108. {
  109. dropDownList.Items.Insert(0, new ListItem("[" + ("Seleccione " + campoAnterior).Trim() + "]", "-1"));
  110. dropDownList.SelectedValue = "-1";
  111. }
  112. }
  113. /// <summary>
  114. /// Binds the combo.
  115. /// </summary>
  116. /// <typeparam name="T"></typeparam>
  117. /// <param name="dropDownList">The drop down list.</param>
  118. /// <param name="lista">The lista.</param>
  119. /// <param name="fieldId">The field id.</param>
  120. /// <param name="fieldDescription">The field description.</param>
  121. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  122. public static void BindCombo<T>(DropDownList dropDownList, IList<T> lista, string fieldId, string fieldDescription, bool addDefaultValue)
  123. {
  124. BindCombo<T>(dropDownList, lista, fieldId, fieldDescription, addDefaultValue, false, string.Empty);
  125. }
  126. public static void BindCombo<T>(DropDownList dropDownList, IList<T> lista, string fieldId, string fieldDescription, bool addDefaultValue, bool addAllValue)
  127. {
  128. BindCombo<T>(dropDownList, lista, fieldId, fieldDescription, addDefaultValue, addAllValue, string.Empty);
  129. }
  130. /// <summary>
  131. /// Método que realiza el Bind de un DropDownList.
  132. /// </summary>
  133. /// <typeparam name="T"></typeparam>
  134. /// <param name="dropDownList">The drop down list.</param>
  135. /// <param name="lista">The lista.</param>
  136. /// <param name="fieldId">The field id.</param>
  137. /// <param name="fieldDescriptionFirst">The field description first.</param>
  138. /// <param name="fieldDescriptionSecond">The field description second.</param>
  139. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  140. public static void BindCombo<T>(DropDownList dropDownList, IList<T> lista, string fieldId, string fieldDescriptionFirst, string fieldDescriptionSecond, bool addDefaultValue, bool addAllValue)
  141. {
  142. DataView dataView = new DataView(BuildDataTable(lista));
  143. dropDownList.Items.Clear();
  144. dropDownList.DataSource = null;
  145. if (dataView != null)
  146. {
  147. foreach (DataRowView drv in dataView)
  148. dropDownList.Items.Insert(dropDownList.Items.Count, new ListItem(drv.Row[fieldDescriptionFirst].ToString() + " " + drv.Row[fieldDescriptionSecond].ToString(), drv.Row[fieldId].ToString()));
  149. }
  150. SortByText(dropDownList);
  151. if (addDefaultValue)
  152. {
  153. dropDownList.Items.Insert(0, new ListItem("[Seleccione]", "-1"));
  154. dropDownList.SelectedValue = "-1";
  155. }
  156. }
  157. /// <summary>
  158. /// Binds the combo.
  159. /// </summary>
  160. /// <typeparam name="T"></typeparam>
  161. /// <param name="dropDownList">The drop down list.</param>
  162. /// <param name="lista">The lista.</param>
  163. /// <param name="fieldId">The field id.</param>
  164. /// <param name="fieldDescriptionFirst">The field description first.</param>
  165. /// <param name="fieldDescriptionSecond">The field description second.</param>
  166. /// <param name="addDefaultValue">if set to <c>true</c> [add default value].</param>
  167. public static void BindCombo<T>(DropDownList dropDownList, IList<T> lista, string fieldId, string fieldDescriptionFirst, string fieldDescriptionSecond, bool addDefaultValue)
  168. {
  169. BindCombo<T>(dropDownList, lista, fieldId, fieldDescriptionFirst, fieldDescriptionSecond, addDefaultValue, false);
  170. }
  171. // <T> is the type of data in the list.
  172. // If you have a List<int>, for example, then call this as follows:
  173. // List<int> ListOfInt;
  174. // DataTable ListTable = BuildDataTable<int>(ListOfInt);
  175. public static DataTable BuildDataTable<T>(IList<T> lista)
  176. {
  177. //create DataTable Structure
  178. DataTable tbl = CreateTable<T>();
  179. Type entType = typeof(T);
  180. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
  181. //get the list item and add into the list
  182. foreach (T item in lista)
  183. {
  184. DataRow row = tbl.NewRow();
  185. foreach (PropertyDescriptor prop in properties)
  186. {
  187. if (prop.GetValue(item) != null)
  188. row[prop.Name] = prop.GetValue(item);
  189. }
  190. tbl.Rows.Add(row);
  191. }
  192. return tbl;
  193. }
  194. /// <summary>
  195. /// Eliminars the archivos session.
  196. /// </summary>
  197. /// <param name="sessionID">The session ID.</param>
  198. public static void EliminarArchivosSession(string sessionID)
  199. {
  200. GC.WaitForPendingFinalizers();
  201. GC.Collect();
  202. string TmpPath = System.Configuration.ConfigurationManager.AppSettings["oTmpPath"];
  203. string ImgPath = System.Configuration.ConfigurationManager.AppSettings["oImgPath"];
  204. var archivo = "*" + sessionID + "*.png";
  205. if (Directory.Exists(TmpPath))
  206. {
  207. foreach (string item in Directory.GetFiles(TmpPath, archivo, SearchOption.TopDirectoryOnly))
  208. {
  209. File.Delete(item);
  210. }
  211. archivo = "Podio_" + sessionID + ".png";
  212. }
  213. if (Directory.Exists(ImgPath))
  214. {
  215. foreach (string item in Directory.GetFiles(ImgPath, archivo, SearchOption.TopDirectoryOnly))
  216. {
  217. File.Delete(item);
  218. }
  219. if (HttpContext.Current != null)
  220. {
  221. ImgPath = "~/Images/TMP";
  222. if (Directory.Exists(HttpContext.Current.Server.MapPath(ImgPath)))
  223. {
  224. string miruta = HttpContext.Current.Server.MapPath(ImgPath).ToString();
  225. foreach (string item in Directory.GetFiles(miruta, archivo, SearchOption.TopDirectoryOnly))
  226. File.Delete(item);
  227. }
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Creates the table.
  233. /// </summary>
  234. /// <typeparam name="T"></typeparam>
  235. /// <returns></returns>
  236. private static DataTable CreateTable<T>()
  237. {
  238. //T –> ClassName
  239. Type entType = typeof(T);
  240. //set the datatable name as class name
  241. DataTable tbl = new DataTable(entType.Name);
  242. //get the property list
  243. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
  244. foreach (PropertyDescriptor prop in properties)
  245. {
  246. Type propType = prop.PropertyType;
  247. if (propType.IsGenericType &&
  248. propType.GetGenericTypeDefinition() == typeof(Nullable<>))
  249. {
  250. propType = Nullable.GetUnderlyingType(propType);
  251. }
  252. else
  253. {
  254. propType = prop.PropertyType;
  255. }
  256. //add property as column
  257. tbl.Columns.Add(prop.Name, propType);
  258. }
  259. return tbl;
  260. }
  261. /// <summary>
  262. /// Genera los campos de una grilla de forma dinámica, a partir de una Lista pasada por parametro
  263. /// </summary>
  264. /// <typeparam name="T">Tipo de la Lista</typeparam>
  265. /// <param name="lista">The lista.</param>
  266. /// <param name="grilla">The grilla.</param>
  267. /// <returns>La Grilla modificada</returns>
  268. public static GridView GenerarGrilla<T>(List<T> lista, GridView grilla)
  269. {
  270. //Eliminar Columnas Actuales(Opcional):
  271. grilla.Columns.Clear();
  272. Type entType = typeof(T);
  273. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
  274. foreach (PropertyDescriptor prop in properties)
  275. {
  276. TemplateField customField = new TemplateField();
  277. // Create the dynamic templates and assign them to
  278. // the appropriate template property.
  279. customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, prop.Name, prop.PropertyType.Name);
  280. customField.SortExpression = prop.Name;
  281. switch (prop.PropertyType.Name)
  282. {
  283. case "DateTime":
  284. case "Int16":
  285. case "Int32":
  286. case "int":
  287. case "decimal":
  288. case "Decimal":
  289. case "double":
  290. case "Double":
  291. customField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
  292. break;
  293. default:
  294. break;
  295. }
  296. customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, prop.Name.ToUpper(), prop.PropertyType.Name);
  297. // Add the field column to the Columns collection of the
  298. // GridView control.
  299. customField.SortExpression = prop.Name;
  300. grilla.Columns.Add(customField);
  301. //grilla.Columns[grilla.Columns.Count - 1].SortExpression = prop.Name;
  302. }
  303. grilla.AllowSorting = true;
  304. return grilla;
  305. }
  306. /// <summary>
  307. /// Genera los campos de una grilla de forma dinámica, a partir de un datatable pasado por parametro
  308. /// </summary>
  309. /// <param name="grilla">The grilla.</param>
  310. /// <param name="tablaGrilla">The tabla grilla.</param>
  311. /// <returns>La Grilla modificada</returns>
  312. public static GridView GenerarGrilla(GridView grilla, DataTable tablaGrilla)
  313. {
  314. grilla.Columns.Clear();
  315. foreach (DataColumn columna in tablaGrilla.Columns)
  316. {
  317. TemplateField customField = new TemplateField();
  318. // Create the dynamic templates and assign them to
  319. // the appropriate template property.
  320. customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, columna.ColumnName, columna.DataType.Name);
  321. customField.SortExpression = columna.ColumnName;
  322. switch (columna.DataType.Name)
  323. {
  324. case "DateTime":
  325. case "Int16":
  326. case "Int32":
  327. case "int":
  328. case "decimal":
  329. case "Decimal":
  330. case "double":
  331. case "Double":
  332. customField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
  333. break;
  334. default:
  335. break;
  336. }
  337. customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, columna.ColumnName.ToUpper(), columna.DataType.Name);
  338. // Add the field column to the Columns collection of the
  339. // GridView control.
  340. grilla.Columns.Add(customField);
  341. }
  342. grilla.AllowSorting = true;
  343. return grilla;
  344. }
  345. /// <summary>
  346. /// Strings the wrap.
  347. /// </summary>
  348. /// <param name="srcStr">The SRC STR.</param>
  349. /// <param name="maxWidth">Width of the max.</param>
  350. /// <returns></returns>
  351. public static List<string> StringWrap(string srcStr, int maxWidth)
  352. {
  353. List<string> lstLines = new List<string>();
  354. int spcCount = 0;
  355. if (!string.IsNullOrEmpty(srcStr))
  356. {
  357. string[] Lines = srcStr.Split(new char[] { '\n', '\r' });
  358. foreach (string Line in Lines)
  359. {
  360. string[] Words = Line.Split(' ');
  361. string curLine = "";
  362. foreach (var word in Words)
  363. {
  364. spcCount = (curLine.Length > 0 ? 1 : 0);
  365. if (curLine.Length + word.Length + spcCount > maxWidth && !string.IsNullOrEmpty(curLine))
  366. {
  367. lstLines.Add(curLine.PadRight(maxWidth));
  368. curLine = "";
  369. }
  370. if (word.Length <= maxWidth)
  371. {
  372. //if length of a word is <= to specified width
  373. if (string.IsNullOrEmpty(curLine))
  374. curLine = word;
  375. else
  376. curLine += " " + word;
  377. }
  378. else
  379. {
  380. //force a word to split if it is > to specified width
  381. if (!string.IsNullOrEmpty(curLine))
  382. {
  383. lstLines.Add(curLine.PadRight(maxWidth));
  384. curLine = "";
  385. }
  386. for (int j = 0; j < word.Length; j += maxWidth)
  387. {
  388. if (j + maxWidth < word.Length)
  389. lstLines.Add(word.Substring(j, maxWidth));
  390. else
  391. lstLines.Add(word.Substring(j).PadRight(maxWidth));
  392. }
  393. }
  394. }
  395. if (!string.IsNullOrEmpty(curLine))
  396. lstLines.Add(curLine.PadRight(maxWidth));
  397. }
  398. }
  399. return lstLines;
  400. }
  401. #region sorting methods
  402. /// <summary>
  403. /// Sorts the by value.
  404. /// </summary>
  405. /// <param name="combo">The combo.</param>
  406. public static void SortByValue(ListControl combo)
  407. {
  408. SortCombo(combo, new ComboValueComparer());
  409. }
  410. /// <summary>
  411. /// Sorts the by text.
  412. /// </summary>
  413. /// <param name="combo">The combo.</param>
  414. public static void SortByText(ListControl combo)
  415. {
  416. SortCombo(combo, new ComboTextComparer());
  417. }
  418. #endregion
  419. #region Private Methods - for internal use
  420. /// <summary>
  421. /// Sorts the combo.
  422. /// </summary>
  423. /// <param name="combo">The combo.</param>
  424. /// <param name="comparer">The comparer.</param>
  425. private static void SortCombo(ListControl combo, IComparer comparer)
  426. {
  427. int i;
  428. if (combo.Items.Count <= 1)
  429. return;
  430. ArrayList arrItems = new ArrayList();
  431. for (i = 0; i < combo.Items.Count; i++)
  432. {
  433. ListItem item = combo.Items[i];
  434. arrItems.Add(item);
  435. }
  436. arrItems.Sort(comparer);
  437. combo.Items.Clear();
  438. for (i = 0; i < arrItems.Count; i++)
  439. {
  440. combo.Items.Add((ListItem)arrItems[i]);
  441. }
  442. }
  443. #endregion
  444. }
  445. #region Combo Comparers
  446. /// <summary>
  447. /// compare list items by their value
  448. /// </summary>
  449. class ComboValueComparer : IComparer
  450. {
  451. public enum SortOrder
  452. {
  453. Ascending = 1,
  454. Descending = -1
  455. }
  456. private int _modifier;
  457. public ComboValueComparer()
  458. {
  459. _modifier = (int)SortOrder.Ascending;
  460. }
  461. public ComboValueComparer(SortOrder order)
  462. {
  463. _modifier = (int)order;
  464. }
  465. //sort by value
  466. public int Compare(Object o1, Object o2)
  467. {
  468. ListItem cb1 = (ListItem)o1;
  469. ListItem cb2 = (ListItem)o2;
  470. return Convert.ToInt32(cb1.Value).CompareTo(Convert.ToInt32(cb2.Value)) * _modifier;
  471. //return cb1.Value.CompareTo(cb2.Value) * _modifier;
  472. }
  473. } //end class ComboValueComparer
  474. /// <summary>
  475. /// compare list items by their text.
  476. /// </summary>
  477. class ComboTextComparer : IComparer
  478. {
  479. public enum SortOrder
  480. {
  481. Ascending = 1,
  482. Descending = -1
  483. }
  484. private int _modifier;
  485. public ComboTextComparer()
  486. {
  487. _modifier = (int)SortOrder.Ascending;
  488. }
  489. public ComboTextComparer(SortOrder order)
  490. {
  491. _modifier = (int)order;
  492. }
  493. //sort by value
  494. public int Compare(Object o1, Object o2)
  495. {
  496. ListItem cb1 = (ListItem)o1;
  497. ListItem cb2 = (ListItem)o2;
  498. return cb1.Text.CompareTo(cb2.Text) * _modifier;
  499. }
  500. } //end class ComboTextComparer
  501. #endregion
  502. /// <summary>
  503. /// Create a template class to represent a dynamic template column.
  504. /// </summary>
  505. class GridViewTemplate : ITemplate
  506. {
  507. private DataControlRowType templateType;
  508. private string columnName;
  509. private string columnType;
  510. /// <summary>
  511. /// Initializes a new instance of the <see cref="GridViewTemplate"/> class.
  512. /// </summary>
  513. /// <param name="type">The type.</param>
  514. /// <param name="colname">The colname.</param>
  515. /// <param name="colType">Type of the col.</param>
  516. public GridViewTemplate(DataControlRowType type, string colname, string colType)
  517. {
  518. templateType = type;
  519. columnName = colname;
  520. columnType = colType;
  521. }
  522. /// <summary>
  523. /// Cuando se implementa mediante una clase, define el objeto <see cref="T:System.Web.UI.Control"/> al que pertenecen los controles secundarios y las plantillas.Estos controles secundarios están a su vez definidos en una plantilla en línea.
  524. /// </summary>
  525. /// <param name="container">Objeto <see cref="T:System.Web.UI.Control"/> que contiene las instancias de los controles de la plantilla en línea.</param>
  526. public void InstantiateIn(System.Web.UI.Control container)
  527. {
  528. // Create the content for the different row types.
  529. switch (templateType)
  530. {
  531. case DataControlRowType.Header:
  532. // Create the controls to put in the header
  533. // section and set their properties.
  534. LinkButton lc = new LinkButton();
  535. lc.Text = "<b>" + columnName + "</b>";
  536. lc.CommandArgument = columnName;
  537. // Add the controls to the Controls collection
  538. // of the container.
  539. container.Controls.Add(lc);
  540. break;
  541. case DataControlRowType.DataRow:
  542. // Create the controls to put in a data row
  543. // section and set their properties.
  544. Label lblFila = new Label();
  545. Literal spacer = new Literal();
  546. spacer.Text = " ";
  547. // To support data binding, register the event-handling methods
  548. // to perform the data binding. Each control needs its own event
  549. // handler.
  550. lblFila.DataBinding += new EventHandler(this.row_DataBinding);
  551. // Add the controls to the Controls collection
  552. // of the container.
  553. container.Controls.Add(lblFila);
  554. break;
  555. // Insert cases to create the content for the other
  556. // row types, if desired.
  557. default:
  558. // Insert code to handle unexpected values.
  559. break;
  560. }
  561. }
  562. /// <summary>
  563. /// Handles the DataBinding event of the row control.
  564. /// </summary>
  565. /// <param name="sender">The source of the event.</param>
  566. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  567. private void row_DataBinding(Object sender, EventArgs e)
  568. {
  569. // Get the Label control to bind the value. The Label control
  570. // is contained in the object that raised the DataBinding
  571. // event (the sender parameter).
  572. Label l = (Label)sender;
  573. // Get the GridViewRow object that contains the Label control.
  574. GridViewRow row = (GridViewRow)l.NamingContainer;
  575. // Get the field value from the GridViewRow object and
  576. // assign it to the Text property of the Label control.
  577. switch (columnType)
  578. {
  579. case "DateTime":
  580. l.Text = DataBinder.Eval(row.DataItem, columnName, "{0:d}").ToString();
  581. break;
  582. default:
  583. l.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
  584. break;
  585. }
  586. }
  587. }
  588. [Serializable]
  589. public struct TablaGrafico
  590. {
  591. public string titulo { get; set; }
  592. public List<string> listaEncabezados { get; set; }
  593. public List<List<string>> listaCuerpo { get; set; }
  594. public List<string> listaPie { get; set; }
  595. }
  596. public static class ProductsSelectionManager
  597. {
  598. public static void KeepSelection(GridView grid, string SessionVariable)
  599. {
  600. //
  601. // se obtienen los id de producto checkeados de la pagina actual
  602. //
  603. List<int> checkedProd = (from item in grid.Rows.Cast<GridViewRow>()
  604. let check = (CheckBox)item.FindControl("chkSelection")
  605. where check.Checked
  606. select Convert.ToInt32(grid.DataKeys[item.RowIndex].Value)).ToList();
  607. //
  608. // se recupera de session la lista de seleccionados previamente
  609. //
  610. List<int> productsIdSel = HttpContext.Current.Session[SessionVariable] as List<int>;
  611. if (productsIdSel == null)
  612. productsIdSel = new List<int>();
  613. //
  614. // se cruzan todos los registros de la pagina actual del gridview con la lista de seleccionados,
  615. // si algun item de esa pagina fue marcado previamente no se devuelve
  616. //
  617. productsIdSel = (from item in productsIdSel
  618. join item2 in grid.Rows.Cast<GridViewRow>()
  619. on item equals Convert.ToInt32(grid.DataKeys[item2.RowIndex].Value) into g
  620. where !g.Any()
  621. select item).ToList();
  622. //
  623. // se agregan los seleccionados
  624. //
  625. productsIdSel.AddRange(checkedProd);
  626. HttpContext.Current.Session[SessionVariable] = productsIdSel;
  627. }
  628. public static void RestoreSelection(GridView grid, string SessionVariable)
  629. {
  630. List<int> productsIdSel = HttpContext.Current.Session[SessionVariable] as List<int>;
  631. if (productsIdSel == null)
  632. return;
  633. //
  634. // se comparan los registros de la pagina del grid con los recuperados de la Session
  635. // los coincidentes se devuelven para ser seleccionados
  636. //
  637. List<GridViewRow> result = (from item in grid.Rows.Cast<GridViewRow>()
  638. join item2 in productsIdSel
  639. on Convert.ToInt32(grid.DataKeys[item.RowIndex].Value) equals item2 into g
  640. where g.Any()
  641. select item).ToList();
  642. //
  643. // se recorre cada item para marcarlo
  644. //
  645. result.ForEach(x => ((CheckBox)x.FindControl("chkSelection")).Checked = true);
  646. }
  647. }
  648. }