none
Ordenar registros en DataGridview RRS feed

  • Pregunta

  •  

    Buenas... comunmente cuando llenaba un datagriview con registros provenientes de un DataTable tenia la opcion de ordenarlos haciendo clik en la cabecera de cada columna.

    Ahora, cuando lleno un datagridview con data desde una coleccion List<T> por que no tengo esa opcion... es posible realizar dicho orden en los registros...?

    Gracias

    sábado, 15 de marzo de 2008 6:18

Respuestas

  • Aqui le va mi socio el código de la clase SortabeSearchableList, pense que lo tenías

    Code Snippet

    public class SortableSearchableList<T> : BindingList<T>
        {
            public SortableSearchableList()
            {

            }

            public SortableSearchableList(IEnumerable<T> collection)
            {
                foreach (T t in collection)
                {
                    this.Add(t);
                }
            }

            public override void EndNew(int itemIndex)
            {
                if (sortPropertyValue != null && itemIndex == this.Count - 1)
                    ApplySortCore(this.sortPropertyValue, this.sortDirectionValue);
                base.EndNew(itemIndex);
            }

            ListSortDirection sortDirectionValue;
            PropertyDescriptor sortPropertyValue;
            bool isSortedValue;

            protected override bool SupportsSortingCore
            {
                get { return true; }
            }

            protected override bool SupportsSearchingCore
            {
                get
                {
                    return true;
                }
            }

            protected override PropertyDescriptor SortPropertyCore
            {
                get { return sortPropertyValue; }
            }

            protected override ListSortDirection SortDirectionCore
            {
                get { return sortDirectionValue; }
            }

            protected override bool IsSortedCore
            {
                get { return isSortedValue; }
            }

            public void RemoveSort()
            {
                RemoveSortCore();
            }

            //private ArrayList sortedList;
            ArrayList unsortedItems;

            protected override void ApplySortCore(PropertyDescriptor prop,
                ListSortDirection direction)
            {
                ArrayList sortedList = new ArrayList();
                // Check to see if the property type we are sorting by implements
                // the IComparable interface.
                Type interfaceType = prop.PropertyType.GetInterface("IComparable");

                if (interfaceType != null)
                {
                    // If so, set the SortPropertyValue and SortDirectionValue.
                    sortPropertyValue = prop;
                    sortDirectionValue = direction;
                    isSortedValue = true;

                    unsortedItems = new ArrayList(this.Count);

                    // Loop through each item, adding it the the sortedItems ArrayList.
                    foreach (Object item in this.Items)
                    {
                        sortedList.Add(prop.GetValue(item));
                        unsortedItems.Add(item);
                    }

                    // Call Sort on the ArrayList.
                    sortedList.Sort();
                    T temp;

                    // Check the sort direction and then copy the sorted items
                    // back into the list.
                    if (direction == ListSortDirection.Descending)
                        sortedList.Reverse();

                    for (int i = 0; i < this.Count; i++)
                    {
                        int position = Find(prop.Name, sortedList[i], i);
                        if (position != i && position > i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = temp;
                        }
                    }
                    // Raise the ListChanged event so bound controls refresh their
                    // values.
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
                else
                    // If the property type does not implement IComparable, let the user
                    // know.
                    throw new NotSupportedException("Cannot sort by " + prop.Name + ". This" +
                        prop.PropertyType.ToString() + " does not implement IComparable");
            }

            protected override void RemoveSortCore()
            {
                int position;
                object temp;
                // Ensure the list has been sorted.
                if (unsortedItems != null)
                {
                    // Loop through the unsorted items and reorder the
                    // list per the unsorted list.
                    for (int i = 0; i < unsortedItems.Count; )
                    {
                        position = this.Find(sortPropertyValue.Name,
                            unsortedItems[i].GetType().
                            GetProperty(sortPropertyValue.Name).GetValue(unsortedItems[i], null), i);
                        if (position >= 0 && position != i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = (T)temp;
                            i++;
                        }
                        else if (position == i)
                            i++;
                        else
                            // If an item in the unsorted list no longer exists, delete it.
                            unsortedItems.RemoveAt(i);
                    }
                    isSortedValue = false;
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
            }

            protected override int FindCore(PropertyDescriptor prop, object key)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = 0; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            private int FindCore(PropertyDescriptor prop, object key, int index)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = index; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            public int Find(string property, object key)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key);
            }

            public int Find(string property, object key, int fromIndex)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key, fromIndex);
            }
        }

     

     

    René Orellana

    miércoles, 19 de marzo de 2008 14:11

Todas las respuestas

  •  

    Una respuesta por alli...
    domingo, 16 de marzo de 2008 4:20
  • Para que te funcione un ordenamiento por culaquien columna utilizando DataBinding en mi caso me ha funcionado utilizanddo una lista de tipo SortableSearchableList. Para mejor explicación aqui va un ejemplo:

     

    Supongamos que queremos llenar un grid con una lista de personas:

     

    List<Persona> listaPersonas = new List<Persona>();

    listaPersonas.Add(new Persona("Maria", "Torres"));

    listaPersonas.Add(new Persona("Mario", "Molina"));

    listaPersonas.Add(new Persona("Rene", "Orellana"));

    listaPersonas.Add(new Persona("Richard", "Toscano"));

     

    SortableSearchableList<Persona> personas = new SortableSearchableList<Persona>(listaPersonas);

     

    DataGridView.DataSourse = personas;

    (en caso de trabajar directamente con el grid SIN BindingSource)

     

    Or

     

    BindingSource.DataSource = personas;

    (en caso de trabajar CON una fuente de datos de tipo BindingSource, pero debemos tomar encuenta que el DataGridView debe estar enlazado a dicha fuente de datos en las propiedades DataSource del control del DataGridView)

     

     

    Espero que te sirva de ayuda.

     

    René Orellana

    miércoles, 19 de marzo de 2008 2:37
  • En primer lugar, gracias por responder.

    Bueno... continuando. . . no puedo ubicar la clase SortableSearchableList ....

     

     
    Code Snippet

    SortableSearchableList<Persona> personas = new SortableSearchableList<Persona>(listaPersonas);

     

     

    Gracias.
    miércoles, 19 de marzo de 2008 3:29
  • Aqui le va mi socio el código de la clase SortabeSearchableList, pense que lo tenías

    Code Snippet

    public class SortableSearchableList<T> : BindingList<T>
        {
            public SortableSearchableList()
            {

            }

            public SortableSearchableList(IEnumerable<T> collection)
            {
                foreach (T t in collection)
                {
                    this.Add(t);
                }
            }

            public override void EndNew(int itemIndex)
            {
                if (sortPropertyValue != null && itemIndex == this.Count - 1)
                    ApplySortCore(this.sortPropertyValue, this.sortDirectionValue);
                base.EndNew(itemIndex);
            }

            ListSortDirection sortDirectionValue;
            PropertyDescriptor sortPropertyValue;
            bool isSortedValue;

            protected override bool SupportsSortingCore
            {
                get { return true; }
            }

            protected override bool SupportsSearchingCore
            {
                get
                {
                    return true;
                }
            }

            protected override PropertyDescriptor SortPropertyCore
            {
                get { return sortPropertyValue; }
            }

            protected override ListSortDirection SortDirectionCore
            {
                get { return sortDirectionValue; }
            }

            protected override bool IsSortedCore
            {
                get { return isSortedValue; }
            }

            public void RemoveSort()
            {
                RemoveSortCore();
            }

            //private ArrayList sortedList;
            ArrayList unsortedItems;

            protected override void ApplySortCore(PropertyDescriptor prop,
                ListSortDirection direction)
            {
                ArrayList sortedList = new ArrayList();
                // Check to see if the property type we are sorting by implements
                // the IComparable interface.
                Type interfaceType = prop.PropertyType.GetInterface("IComparable");

                if (interfaceType != null)
                {
                    // If so, set the SortPropertyValue and SortDirectionValue.
                    sortPropertyValue = prop;
                    sortDirectionValue = direction;
                    isSortedValue = true;

                    unsortedItems = new ArrayList(this.Count);

                    // Loop through each item, adding it the the sortedItems ArrayList.
                    foreach (Object item in this.Items)
                    {
                        sortedList.Add(prop.GetValue(item));
                        unsortedItems.Add(item);
                    }

                    // Call Sort on the ArrayList.
                    sortedList.Sort();
                    T temp;

                    // Check the sort direction and then copy the sorted items
                    // back into the list.
                    if (direction == ListSortDirection.Descending)
                        sortedList.Reverse();

                    for (int i = 0; i < this.Count; i++)
                    {
                        int position = Find(prop.Name, sortedList[i], i);
                        if (position != i && position > i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = temp;
                        }
                    }
                    // Raise the ListChanged event so bound controls refresh their
                    // values.
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
                else
                    // If the property type does not implement IComparable, let the user
                    // know.
                    throw new NotSupportedException("Cannot sort by " + prop.Name + ". This" +
                        prop.PropertyType.ToString() + " does not implement IComparable");
            }

            protected override void RemoveSortCore()
            {
                int position;
                object temp;
                // Ensure the list has been sorted.
                if (unsortedItems != null)
                {
                    // Loop through the unsorted items and reorder the
                    // list per the unsorted list.
                    for (int i = 0; i < unsortedItems.Count; )
                    {
                        position = this.Find(sortPropertyValue.Name,
                            unsortedItems[i].GetType().
                            GetProperty(sortPropertyValue.Name).GetValue(unsortedItems[i], null), i);
                        if (position >= 0 && position != i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = (T)temp;
                            i++;
                        }
                        else if (position == i)
                            i++;
                        else
                            // If an item in the unsorted list no longer exists, delete it.
                            unsortedItems.RemoveAt(i);
                    }
                    isSortedValue = false;
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
            }

            protected override int FindCore(PropertyDescriptor prop, object key)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = 0; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            private int FindCore(PropertyDescriptor prop, object key, int index)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = index; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            public int Find(string property, object key)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key);
            }

            public int Find(string property, object key, int fromIndex)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key, fromIndex);
            }
        }

     

     

    René Orellana

    miércoles, 19 de marzo de 2008 14:11
  • OK. Gracias. Funcionó de maravilla.

    lunes, 24 de marzo de 2008 3:21
  • Aqui le va mi socio el código de la clase SortabeSearchableList, pense que lo tenías

    Code Snippet

    public class SortableSearchableList<T> : BindingList<T>
        {
            public SortableSearchableList()
            {

            }

            public SortableSearchableList(IEnumerable<T> collection)
            {
                foreach (T t in collection)
                {
                    this.Add(t);
                }
            }

            public override void EndNew(int itemIndex)
            {
                if (sortPropertyValue != null && itemIndex == this.Count - 1)
                    ApplySortCore(this.sortPropertyValue, this.sortDirectionValue);
                base.EndNew(itemIndex);
            }

            ListSortDirection sortDirectionValue;
            PropertyDescriptor sortPropertyValue;
            bool isSortedValue;

            protected override bool SupportsSortingCore
            {
                get { return true; }
            }

            protected override bool SupportsSearchingCore
            {
                get
                {
                    return true;
                }
            }

            protected override PropertyDescriptor SortPropertyCore
            {
                get { return sortPropertyValue; }
            }

            protected override ListSortDirection SortDirectionCore
            {
                get { return sortDirectionValue; }
            }

            protected override bool IsSortedCore
            {
                get { return isSortedValue; }
            }

            public void RemoveSort()
            {
                RemoveSortCore();
            }

            //private ArrayList sortedList;
            ArrayList unsortedItems;

            protected override void ApplySortCore(PropertyDescriptor prop,
                ListSortDirection direction)
            {
                ArrayList sortedList = new ArrayList();
                // Check to see if the property type we are sorting by implements
                // the IComparable interface.
                Type interfaceType = prop.PropertyType.GetInterface("IComparable");

                if (interfaceType != null)
                {
                    // If so, set the SortPropertyValue and SortDirectionValue.
                    sortPropertyValue = prop;
                    sortDirectionValue = direction;
                    isSortedValue = true;

                    unsortedItems = new ArrayList(this.Count);

                    // Loop through each item, adding it the the sortedItems ArrayList.
                    foreach (Object item in this.Items)
                    {
                        sortedList.Add(prop.GetValue(item));
                        unsortedItems.Add(item);
                    }

                    // Call Sort on the ArrayList.
                    sortedList.Sort();
                    T temp;

                    // Check the sort direction and then copy the sorted items
                    // back into the list.
                    if (direction == ListSortDirection.Descending)
                        sortedList.Reverse();

                    for (int i = 0; i < this.Count; i++)
                    {
                        int position = Find(prop.Name, sortedList[i], i);
                        if (position != i && position > i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = temp;
                        }
                    }
                    // Raise the ListChanged event so bound controls refresh their
                    // values.
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
                else
                    // If the property type does not implement IComparable, let the user
                    // know.
                    throw new NotSupportedException("Cannot sort by " + prop.Name + ". This" +
                        prop.PropertyType.ToString() + " does not implement IComparable");
            }

            protected override void RemoveSortCore()
            {
                int position;
                object temp;
                // Ensure the list has been sorted.
                if (unsortedItems != null)
                {
                    // Loop through the unsorted items and reorder the
                    // list per the unsorted list.
                    for (int i = 0; i < unsortedItems.Count; )
                    {
                        position = this.Find(sortPropertyValue.Name,
                            unsortedItems[i].GetType().
                            GetProperty(sortPropertyValue.Name).GetValue(unsortedItems[i], null), i);
                        if (position >= 0 && position != i)
                        {
                            temp = this[i];
                            this[i] = this[position];
                            this[position] = (T)temp;
                            i++;
                        }
                        else if (position == i)
                            i++;
                        else
                            // If an item in the unsorted list no longer exists, delete it.
                            unsortedItems.RemoveAt(i);
                    }
                    isSortedValue = false;
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
            }

            protected override int FindCore(PropertyDescriptor prop, object key)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = 0; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            private int FindCore(PropertyDescriptor prop, object key, int index)
            {
                // Get the property info for the specified property.
                PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
                T item;

                if (key != null)
                {
                    // Loop through the the items to see if the key
                    // value matches the property value.
                    for (int i = index; i < Count; ++i)
                    {
                        item = (T)Items[i];
                        if (propInfo.GetValue(item, null).Equals(key))
                            return i;
                    }
                }
                return -1;
            }

            public int Find(string property, object key)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key);
            }

            public int Find(string property, object key, int fromIndex)
            {
                // Check the properties for a property with the specified name.
                PropertyDescriptorCollection properties =
                    TypeDescriptor.GetProperties(typeof(T));
                PropertyDescriptor prop = properties.Find(property, true);

                // If there is not a match, return -1 otherwise pass search to
                // FindCore method.
                if (prop == null)
                    return -1;
                else
                    return FindCore(prop, key, fromIndex);
            }
        }

     

     

     

    René Orellana

    r3n3 un saludo y una duda, tu clase funciona de maravilla pero en framework 3.5 (almenos en ese lo probe) pero con vs2010 en framework 4.0 da un errores en unos items que en 4.0 son null por default, no tnedras la clase actualizada para 4.0 ? un saludo
    jueves, 28 de abril de 2011 4:29