How to do Search and sort of TemplateFields in a GridView?

2

Basically, I have a table (GridView) on an aspx page whose data is defined by TemplateFields. For example:

<asp:GridView runat="server" ID="grdProdutos">
    <Columns>
        <asp:TemplateField HeaderText="Produto">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblProduto" Text='<%# Eval("NomeProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Tipo">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblTipo" Text='<%# Eval("TipoProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Preço">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblPreco" Text='<%# Eval("PrecoProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

The methods used in code behind are as follows:

RepositorioProdutos banco = new RepositorioProdutos();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CarregarGridView();
    }
}

public void CarregarGridView()
{
    var produtos = banco.ObterProdutos();

    if (produtos != null)
    {
        grdProdutos.DataSource = produtos;
        grdProdutos.DataBind();
    }
    else
    {
        throw new Exception("Nenhum produto encontrado.");
    }
}

I would like to know how I could implement a product search (looking for a term in any field) and how I could implement a sort order by clicking the column name I'd like to sort (like in Windows Explorer), without needing (ie without having to access the banco.ObterProdutos() method again).

Note: For the search, I'm considering using a textBox that will be used to enter the search keyword, and a button that will trigger the search.

    
asked by anonymous 02.04.2014 / 19:30

2 answers

4

There are two distinct questions, in my opinion it is not a simple task when it seems, so this answer is not meant to be definitive, but just try to show a starting point.

About sorting:

The GridView has a OnSorting event that provides a parameter with a SortExpression questration property that contains a string normally with the name of the field to be sorted.

It is not possible to sort the fields from a string, so we need a System.Linq.Dynamic library that allows us to use strings instead of lambda expressions.

So, install the System.Linq.Dynamic library through nuget, then make sure to reference your code:

using System.Linq.Dynamic;

Now change your gridView to accept sorting:

<asp:GridView ID="grdProdutos" AllowSorting="true" OnSorting="gridView_Sorting" runat="server">

In the columns of the gridView we need to define the SortExpression which tells us which fields we want to sort:

<asp:TemplateField HeaderText="Produto" SortExpression="Produto">

And in your codebehind:

protected void grdProdutos_Sorting(object sender, GridViewSortEventArgs e)
{
    var gridView = (GridView)sender;

    for (int i = 0; i < gridView.Columns.Count; i++)
        if (gridView.Columns[i].SortExpression == e.SortExpression)
            if (e.SortExpression.EndsWith(" desc"))
                gridView.Columns[i].SortExpression = e.SortExpression.Replace(" desc", "");
            else
                gridView.Columns[i].SortExpression = e.SortExpression + " desc";


    gridView.DataSource = banco.ObterProdutos().OrderBy(e.SortExpression);        
    gridView.DataBind();
}

Remembering that Dynamic Linq works with types IQueryable<T> , so if your ObterProdutos method returns a IEnumerable<T> modify it, probably avoiding making a call to ToList() .

To search you can do with the input and a button to stop firing and use the value of the input to search, then set the DataSource again, for example:

gridView.DataSource = banco.ObterProdutos().Where(m => m.Produto.StartsWith(valordoinput);
gridView.DataBind();

The boring part will be keeping the search and sort together. You would need to create a method that will fetch the SortExpression from each of the gridView columns as well as the search expression that returns a list of products with Where and OrderBy .

    
02.04.2014 / 21:47
0

If the Grid is already populated you can use the grid's own ds to retrieve the information without having to search the base again .. I believe this would work ..

 IList<seuObj> variavel = this.GridView1.DataSource as IList<seuObj>;

 if (variavel != null){
     GridView1.DataSource = variavel.OrderBy(x => x.campo).ToList();
     GridView1.DataBind();
 }
    
12.05.2015 / 18:46