Foros del Web » Programando para Internet » ASPX (.net) »

Personalizar Gridview con Collections Generic

Estas en el tema de Personalizar Gridview con Collections Generic en el foro de ASPX (.net) en Foros del Web. Bueno amigos les quiero pedir su ayuda lo que pasa que tengo un codigo para personalizar un gridview y que soporta un array de objetos ...
  #1 (permalink)  
Antiguo 24/07/2007, 11:58
Avatar de Jackpat  
Fecha de Ingreso: noviembre-2004
Mensajes: 55
Antigüedad: 21 años, 10 meses
Puntos: 0
Personalizar Gridview con Collections Generic

Bueno amigos les quiero pedir su ayuda lo que pasa que tengo un codigo para personalizar un gridview y que soporta un array de objetos para desplegarlos en un gridview, el cual es el siguiente:

Código PHP:
namespace CustomControls
{
    public class 
GridViewEx : GridView
    
{
        
#region Array Comparer

        
private class ArrayComparer : IComparer
        
{
            private 
string sortedPropertyName = null;
            private 
SortDirection sortDirection = SortDirection.Ascending;

            public 
ArrayComparer(string sortedPropertyName, SortDirection sortDirection)
            {
                
this.sortedPropertyName = sortedPropertyName;
                
this.sortDirection = sortDirection;
            }


            
#region IComparer Members

            
public int Compare(object x, object y)
            {
                
PropertyInfo prop = x.GetType().GetProperty(sortedPropertyName);
                
                if (
prop == null)
                    throw new 
Exception(string.Format("Incorrect property to sort: {0}", sortedPropertyName));

                
object xValue = prop.GetValue(x, null);
                
object yValue = prop.GetValue(y, null);

                if (
xValue == null || yValue == null)
                    throw new 
Exception(string.Format("Failed to sort by {0}", sortedPropertyName));

                if (
sortDirection == SortDirection.Ascending)
                    return ((
IComparable)xValue).CompareTo(((IComparable)yValue));
                else
                    return ((
IComparable)yValue).CompareTo(((IComparable)xValue));
            }

            
#endregion
        
}

        
#endregion

        #region Event Handlers

        
protected override void OnInit(EventArgs e)
        {
            
base.OnInit(e);
            
this.Sorting += new GridViewSortEventHandler(GridViewEx_Sorting);
            
this.PageIndexChanging += new GridViewPageEventHandler(GridViewEx_PageIndexChanging);
        }

        
void GridViewEx_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            
this.PageIndex = e.NewPageIndex;
            
            
BindDataSource();
        }

        
void GridViewEx_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (
PrevSortExpression == e.SortExpression)
            {
                
e.SortDirection = SortDirection.Descending;
                
PrevSortExpression = null;
            }
            else
                
PrevSortExpression = e.SortExpression;
            
CurrentSortExpression = e.SortExpression;
            
CurrentSortDirection = e.SortDirection;
            
ChangeHeaders(this.HeaderRow);

            
BindDataSource();
        }

        
#endregion

        #region Private

        
private void ChangeHeaders(GridViewRow headerRow)
        {
            for (
int i = 0; i < headerRow.Cells.Count; i++)
            {
                if (
headerRow.Cells[i] is DataControlFieldCell)
                {
                    
DataControlField field = ((DataControlFieldCell)headerRow.Cells[i]).ContainingField;

                    
Regex r = new Regex(@"\s(\u25bc|\u25b2)");
                    
field.HeaderText = r.Replace(field.HeaderText, "");

                    if (
field.SortExpression != null && field.SortExpression == CurrentSortExpression)
                    {
                        if (
CurrentSortDirection == SortDirection.Ascending)
                            
field.HeaderText += " \u25b2";
                        else
                            
field.HeaderText += " \u25bc";
                    }
                }
            }
        }

        private 
string PrevSortExpression
        
{
            
get
            
{
                if (
ViewState["PrevSortExpression"] == null)
                    return 
null;
                return (string)
ViewState["PrevSortExpression"];
            }
            
set
            
{
                
ViewState["PrevSortExpression"] = value;
            }
        }

        private 
string CurrentSortExpression
        
{
            
get
            
{
                if (
ViewState["CurrentSortExpression"] == null)
                    return 
null;
                return (string)
ViewState["CurrentSortExpression"];
            }
            
set
            
{
                
ViewState["CurrentSortExpression"] = value;
            }
        }

        private 
SortDirection CurrentSortDirection
        
{
            
get
            
{
                if (
ViewState["CurrentSortDirection"] == null)
                    return 
SortDirection.Ascending;
                return (
SortDirection)ViewState["CurrentSortDirection"];
            }
            
set
            
{
                
ViewState["CurrentSortDirection"] = value;
            }
        }


        
#endregion

        #region Public 

        /// <summary>
        /// Binds the data source to the GridView control.
        /// </summary>
        
public void BindDataSource()
        {
            Array 
dataSource = null;
            if (
DataSourceRequested != null)
                
DataSourceRequested(out dataSource);

            if (
dataSource == null)
                throw new 
Exception("Failed to get data source.");

            if (
CurrentSortExpression != null)
            {
                
ArrayList ar = new ArrayList(dataSource);
                
ar.Sort(new ArrayComparer(CurrentSortExpression, CurrentSortDirection));
                
dataSource = ar.ToArray();
            }

            
base.DataSource = dataSource;
            
base.DataBind();
        }

        
/// <summary>
        /// Occurs when the data source is requested.
        /// </summary>
        
public event DataSourceRequestedEventHandler DataSourceRequested;

        
#endregion
    
}

    
/// <summary>
    /// Represents the method that handles the DataSourceRequested event of a GridView control. 
    /// </summary>
    /// <param name="dataSource">Array of the objects.</param>
    
public delegate void DataSourceRequestedEventHandler(out Array dataSource);
} 
y su utilización:

Código PHP:
    #region Event Handlers

    
protected void Page_Load(object sender, EventArgs e)
    {
        if (!
IsPostBack)
            
gv.BindDataSource();

    }
    protected 
void gv_DataSourceRequested(out Array dataSource)
    {
        
dataSource = GetTestData();
    }

    
#endregion

    #region Private

    
private ProductInfo[] GetTestData()
    {
        
ProductInfo[] res = new ProductInfo[8];
        
res[0] = new ProductInfo("TV-Tuner", 1, 40.00);
        
res[1] = new ProductInfo("Modem", 2, 19.00);
        
res[2] = new ProductInfo("Motherbord", 1, 120.00);
        
res[3] = new ProductInfo("Keyboard", 18, 5.00);
        
res[4] = new ProductInfo("Mouse", 25, 4.99);
        
res[5] = new ProductInfo("Mouse pad", 30, 1.50);
        
res[6] = new ProductInfo("Monitor", 4, 234.00);
        
res[7] = new ProductInfo("Fan", 10, 8.00);
        return 
res;
    }

    
#endregion 
ahora la idea es que se pueda trabajar con collections.Generics, lo he intentado de hacer pero no he logrado que funcione por eso recurro a ustedes para que por ultimo entre todos lo intentemos de hacer.... y para que no se crea que quiero que me hagan la pega aca un ejemplo de lo que he intentado hacer jejeeje....

Código PHP:
   #region Event Handlers

    
protected void Page_Load(object sender, EventArgs e)
    {
        if (!
IsPostBack)
            
gv.BindDataSource();

    }
    protected 
void gv_DataSourceRequested(out List<ProductInfo> dataSource)
    {
        
dataSource = GetTestData();
    }

    
#endregion

    #region Private

    
private ProductInfoCollection<ProductInfo> GetTestData()
    {
        
ProductInfoCollection<ProductInfo> res = new ProductInfoCollection<ProductInfo>();
        
res.Add(new ProductInfo("TV-Tuner", 1, 40.00));
        
res.Add(new ProductInfo("Modem", 2, 19.00));
        
res.Add(new ProductInfo("Motherbord", 1, 120.00));
        
res.Add(new ProductInfo("Keyboard", 18, 5.00));
        
res.Add(new ProductInfo("Mouse", 25, 4.99));
        
res.Add(new ProductInfo("Mouse pad", 30, 1.50));
        
res.Add(new ProductInfo("Monitor", 4, 234.00));
        
res.Add(new ProductInfo("Fan", 10, 8.00));
        return 
res;
    }

    
#endregion 
bueno de la otra parte del codigo estoy es lo unico que tengo la implementacion del IComparer con Generics:
Código PHP:
        #region Generic Comparer

        
public class GenericComparer<T> : IComparer<T>
        {
            private 
string sortExpression;
            private 
SortDirection sortDirection;

            public 
SortDirection SortDirection
            
{
                
get { return this.sortDirection; }
                
set { this.sortDirection = value; }
            }

            public 
GenericComparer() { }

            public 
GenericComparer(string sortExpression, SortDirection sortDirection)
            {
                
this.sortExpression = sortExpression;
                
this.sortDirection = sortDirection;
            }

            
#region IComparer Members

            
public int Compare(T x, T y)
            {
                
PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression);
                
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
                
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
                if (
SortDirection == SortDirection.Ascending)
                {
                    return 
obj1.CompareTo(obj2);
                }
                else return 
obj2.CompareTo(obj1);

            }
            
#endregion
        
} 
        
        
#endregion 
Bueno esperando que me puedan ayudar, de antemano graxxxxx :D
__________________
No abras los labios si no estás seguro de lo que vas a decir, es más hermoso que el silencio.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:46.