PageRenderTime 57ms CodeModel.GetById 19ms app.highlight 30ms RepoModel.GetById 1ms app.codeStats 0ms

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