Binding Radgrid data to Radfilter

5 posts, 0 answers
  1. Joao
    Joao avatar
    14 posts
    Member since:
    Feb 2011

    Posted 08 Apr 2012 Link to this post

    Helo,
    I´m rather new in using Radcontrols. I have a Radgrid with OnNeedDatasource binding beacuse it has parameters only available after the Grid is rendered. Until then the Grid is not visible. After binding the datasource it becames visible.
    The Grid has filtering on all columns, all of them GridDataBound. Four of the columns have custom filtering with RadGrigDropDownEditor as defined in Telerik samples.
    The four dropdowns are created on page_load if not postback with four diferent datasources. OnFilterCration implements them.
    Everything is working fine but I have a litle problem: The DropDowns are showing all the items bound by the respective table loaded with the definition and what I need is to show only the items contained in the Grid datasource...
    I´ve tried OnItemDatabound, wich seemed to be the point in the Grid lifecycle to bind the grid data to the dropdown, but I can´t get it.
    For instance, I have a dataset bound to the grid with sales for two custumer types and when I open the dropdown to select the client type it shows all the client types defined in the aplication. I would like to show only those two types.
    I enclose the meaning part of the code:
    ASPX:

    <telerik:RadAjaxManager runat="server" ID="RadAjaxManager1" DefaultLoadingPanelID="RadAjaxLoadingPanel1">
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="FiltroClientes">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="FiltroClientes" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                    <telerik:AjaxSetting AjaxControlID="ApplyButton">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="CliGrandeza" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                    <telerik:AjaxSetting AjaxControlID="CliGrandeza">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="CliGrandeza" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                </AjaxSettings>
                <ClientEvents OnRequestStart="onRequestStart" />
            </telerik:RadAjaxManager>
             
            <telerik:RadAjaxLoadingPanel runat="server" ID="RadAjaxLoadingPanel1"
                Skin="Default" />
                 
            <telerik:RadWindow ID="RadWindow1" runat="server" Behaviors="Move,Close,Resize" Title="Filtragem da informação:"
                Modal="true" Width="500" Height="350">
                <ContentTemplate>
                    <telerik:RadFilter runat="server" ID="FiltroClientes" FilterContainerID="CliGrandeza" ShowApplyButton="false"
                        OnFieldEditorCreating="FiltroClientes_FieldEditorCreating"
                        Style="margin: 10px 0 0 10px" >
                    </telerik:RadFilter>
                    <asp:Panel ID="FilterButtonPanel" runat="server" Style="margin: 10px 0 0 10px; font-size: medium">
                        <asp:LinkButton runat="server" ID="ApplyButton" OnClick="ApplyButton_Click" Text="Aplicar filtro"
                            OnClientClick="hideFilterBuilderDialog()" />
                    </asp:Panel>
                </ContentTemplate>
            </telerik:RadWindow>
             
            <telerik:RadGrid ID="CliGrandeza" runat="server" AutoGenerateColumns="False" PageSize="20"
                CssClass="BaixaGrid" GridLines="None" AllowPaging="True" AllowSorting="True"
                OnNeedDataSource="CliGrandeza_NeedDataSource" AllowFilteringByColumn="True" ShowGroupPanel="True"
                EnableHeaderContextMenu="True" EnableLinqExpressions="False" OnPreRender="CliGrandeza_PreRender" OnItemDataBound="CliGrandeza_OnItemDataBound"
                ShowFooter="True" CellSpacing="0" ShowStatusBar="True" Width="955px" OnItemCommand="CliGrandeza_ItemCommand">
                 
                <GroupingSettings CaseSensitive="false" ShowUnGroupButton="True" RetainGroupFootersVisibility="true" />
                 
                <MasterTableView DataKeyNames="NumCli" IsFilterItemExpanded="false" Width="100%" ShowGroupFooter="true"
                    CommandItemDisplay="Top" AllowMultiColumnSorting="True" AllowFilteringByColumn="true"
                    NoMasterRecordsText="Não há informação que corresponda à seleção pretendida" >
     
                    <EditFormSettings>
                        <EditColumn FilterControlAltText="Filter EditCommandColumn column" />
                    </EditFormSettings>
     
                    <PagerStyle Mode="NextPrev" />
     
                    <HeaderStyle Font-Bold="true" />
                    <FooterStyle Font-Size="Smaller" Font-Italic="true" Font-Bold="true" />
     
                    <CommandItemSettings
                        ShowAddNewRecordButton="False"
                        ShowExportToCsvButton="True"
                        ShowExportToExcelButton="True"
                        ShowExportToPdfButton="False"
                        ShowExportToWordButton="True" >
                    </CommandItemSettings>
                     
                    <RowIndicatorColumn
                        Visible="False">
                    </RowIndicatorColumn>
     
                    <ExpandCollapseColumn
                        Visible="True"
                        FilterControlAltText="Filter ExpandColumn column">
                    </ExpandCollapseColumn>
     
                    <Columns>
                        <telerik:GridBoundColumn HtmlEncode="true"
                            DataField="NumCli"
                            HeaderText="Cliente"
                            ReadOnly="True"
                            SortExpression="NumCli"
                            UniqueName="NumCli"
                            Aggregate="Count"
                            FooterText="Clientes: "
                            FilterControlAltText="Filter NumCli column">
                            <FooterStyle HorizontalAlign="Left" Width="90px" />
                            <HeaderStyle HorizontalAlign="Left" Width="90px" Wrap="False" />
                            <ItemStyle Font-Size="Smaller" Width="90px" Wrap="False" />
                        </telerik:GridBoundColumn>
     
                        <telerik:GridBoundColumn HtmlEncode="true"
                            DataField="Nome" 
                            HeaderText="Nome"
                            ReadOnly="True"
                            SortExpression="Nome"
                            UniqueName="Nome"
                            DataFormatString="<nobr>{0}</nobr>"
                            FilterControlAltText="Filter Nome column">
                            <FooterStyle HorizontalAlign="Left" Width="470px" />
                            <HeaderStyle HorizontalAlign="Center" Width="470px" Wrap="False" />
                            <ItemStyle Font-Size="Smaller" Wrap="False"/>
                        </telerik:GridBoundColumn>
     
                        <telerik:GridBoundColumn HtmlEncode="true"
                            DataField="Localidade"
                            HeaderText="Localidade"
                            ReadOnly="True"
                            SortExpression="Localidade"
                            UniqueName="Localidade"
                            DataFormatString="<nobr>{0}</nobr>"
                            FilterControlAltText="Filter Localidade column">
                            <FooterStyle HorizontalAlign="Left" Width="170px" />
                            <HeaderStyle HorizontalAlign="Center" Width="170px" Wrap="False" />
                            <ItemStyle Font-Size="Smaller" Wrap="False"/>
                        </telerik:GridBoundColumn>
     
                        <telerik:GridBoundColumn HtmlEncode="true"
                            DataField="Tcliente"
                            HeaderText="Tipo Cliente"
                            ReadOnly="True"
                            UniqueName="Tcliente"
                            Visible="False">
                        </telerik:GridBoundColumn>   
    …..
    <telerik:GridCalculatedColumn
                            Aggregate="Sum"
                            HeaderText="Ano-2"
                            UniqueName="TotalAnoPen"
                            DataType="System.Double"
                            DataFields="Facturas2, Creditos2"
                            Expression="ISNULL({0},0)+ISNULL({1},0)"
                            DataFormatString="<nobr>{0:c}</nobr>"
                            FooterText="Total Ano-2: "
                            SortExpression="TotalAnoPen">
                            <FooterStyle HorizontalAlign="Right" Width="85px" />
                            <HeaderStyle HorizontalAlign="Right" Width="85px" Wrap="False" />
                            <ItemStyle Font-Size="Smaller" HorizontalAlign="Right" Wrap="False"/>
                        </telerik:GridCalculatedColumn>
                         
                    </Columns>
                         
                </MasterTableView>
     
                <GroupingSettings CaseSensitive="False"
                    ShowUngroupButton="true" />
                 
                <ExportSettings FileName="Clientes" HideStructureColumns="true" ExportOnlyData="true"
                    IgnorePaging="True" OpenInNewWindow="true">
                    <Csv ColumnDelimiter="Tab" RowDelimiter="NewLine" FileExtension="TXT" EncloseDataWithQuotes="true" />
                    <Excel FileExtension="xls" Format="Html" />
                </ExportSettings>
                 
                <ClientSettings
                     AllowColumnsReorder="True"
                     ReorderColumnsOnClient="True"
                     EnableRowHoverStyle="false"
                     AllowDragToGroup="True">
     
                    <Selecting AllowRowSelect="True"
                        CellSelectionMode="None"
                        EnableDragToSelectRows="False" />
                     
                    <Scrolling AllowScroll="True"
                        UseStaticHeaders="True"
                        SaveScrollPosition="true"
                        ScrollHeight="500px" />
                    
                    <Resizing
                        EnableRealTimeResize="True"
                        ResizeGridOnColumnResize="True"
                        AllowColumnResize="True"
                        AllowResizeToFit="True" />
                     
                    <Animation AllowColumnReorderAnimation="True" />
                </ClientSettings>
     
                <FilterMenu EnableImageSprites="False" />
     
            </telerik:RadGrid>
             
            <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
                <script type="text/javascript">
                <!--
                    function pageLoad()
                    {
                        var filter = $find("<%=FiltroClientes.ClientID %>");
                        var menu = filter.get_contextMenu();
                        menu.add_showing(FilterMenuShowing);
                    }
     
                    function FilterMenuShowing(sender, args)
                    {
                        var filter = $find("<%=FiltroClientes.ClientID %>");
                        var currentExpandedItem = sender.get_attributes()._data.ItemHierarchyIndex;
                        var fieldName = filter._expressionItems[currentExpandedItem];
                        var allFields = filter._dataFields;
                        if (fieldName == "Tcliente" || fieldName == "TDistrito" || fieldName == "TVolta" || fieldName == "TZona")
                        {
                            for (var i = 0, j = allFields.length; i < j; i++)
                            {
                                if (allFields[i].FieldName == fieldName)
                                {
                                    sender.findItemByValue("StartsWith").set_visible(false);
                                    sender.findItemByValue("EndsWith").set_visible(false);
                                    sender.findItemByValue("GreaterThan").set_visible(false);
                                    sender.findItemByValue("GreaterThanOrEqualTo").set_visible(false);
                                    sender.findItemByValue("LessThan").set_visible(false);
                                    sender.findItemByValue("LessThanOrEqualTo").set_visible(false);
                                    sender.findItemByValue("Contains").set_visible(false);
                                    sender.findItemByValue("DoesNotContain").set_visible(false);
                                    sender.findItemByValue("Between").set_visible(false);
                                    sender.findItemByValue("NotBetween").set_visible(false);
                                }
                            }
                        }
     
                    }
     
                    function openFilterBuilderDialog()
                    {
                        $find('<%=RadWindow1.ClientID %>').show();
                    }
                    function hideFilterBuilderDialog()
                    {
                        $find('<%=RadWindow1.ClientID %>').close();
                    }
     
                    function OnHeaderMenuItemClicked(sender, args)
                    {
                        if (args.get_item().get_value() == "FilterBuilder")
                        {
                            openFilterBuilderDialog();
                        }
                    }
                    function onPanelBarItemClicked(sender, args)
                    {
                        if (args.get_item().get_commandName() == "OpenRadFilter")
                        {
                            openFilterBuilderDialog();
                        }
                    }
                    function onRequestStart(sender, args)
                    {
                        if (args.get_eventTarget().indexOf("ExportToExcelButton") >= 0 ||
                        args.get_eventTarget().indexOf("ExportToWordButton") >= 0 ||
                        args.get_eventTarget().indexOf("ExportToPdfButton") >= 0 ||
                        args.get_eventTarget().indexOf("ExportToCsvButton") >= 0)
                        {
                            args.set_enableAjax(false);
                        }
                    }
     
                    -->
                </script>

    C#:

    public partial class VeMapCliGrandeza : System.Web.UI.Page

        {

            DisPPweb.dal dados = new DisPPweb.dal();

            DateTime dataFim = DateTime.Now;

            DateTime dataIni = IniciaDatas();

     

           protected void CliGrandeza_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)

            {

                CliGrandeza.DataSource = dados.DSvendas3Anos(Session["Grupo"].ToString(), dataIni, dataFim);

            }

     

            protected void Page_Load(object sender, EventArgs e)

            {

                if (!IsPostBack)

                {

                    DataIniBox.SelectedDate = dataIni;

                    DataFimBox.SelectedDate = dataFim;

                    ConfirmaDatasBtn.Enabled = true;

                    CliGrandeza.Visible = false;

                    RadToolBar1.Visible = false;

     

                    RadFilterDropDownEditor dropDownTipoCliente = new RadFilterDropDownEditor();

                    FiltroClientes.FieldEditors.Add(dropDownTipoCliente);

                    dropDownTipoCliente.FieldName = "Tcliente";

                    dropDownTipoCliente.DisplayName = "Tipo de cliente";

                    dropDownTipoCliente.DataTextField = "Tcliente";

                    dropDownTipoCliente.DataValueField = "Tcliente";

                    dropDownTipoCliente.DataSource = dados.GetDataTable("SELECT DISTINCT Texto AS Tcliente FROM dbo.TiposCliente").DefaultView.ToTable(true, "Tcliente");

     

                    RadFilterDropDownEditor dropDownDistrito = new RadFilterDropDownEditor();

                    FiltroClientes.FieldEditors.Add(dropDownDistrito);

                    dropDownDistrito.FieldName = "TDistrito";

                    dropDownDistrito.DisplayName = "Distrito";

                    dropDownDistrito.DataTextField = "TDistrito";

                    dropDownDistrito.DataValueField = "TDistrito";

                    dropDownDistrito.DataSource = dados.GetDataTable("SELECT DISTINCT Texto AS TDistrito FROM dbo.Distritos").DefaultView.ToTable(true, "TDistrito");

     

                    RadFilterDropDownEditor dropDownZona = new RadFilterDropDownEditor();

                    FiltroClientes.FieldEditors.Add(dropDownZona);

                    dropDownZona.FieldName = "TZona";

                    dropDownZona.DisplayName = "Zona";

                    dropDownZona.DataTextField = "TZona";

                    dropDownZona.DataValueField = "TZona";

                    dropDownZona.DataSource = dados.GetDataTable("SELECT DISTINCT Texto AS TZona FROM dbo.Zonas").DefaultView.ToTable(true, "TZona");

     

                    RadFilterDropDownEditor dropDownVolta = new RadFilterDropDownEditor();

                    FiltroClientes.FieldEditors.Add(dropDownVolta);

                    dropDownVolta.FieldName = "TVolta";

                    dropDownVolta.DisplayName = "Volta";

                    dropDownVolta.DataTextField = "TVolta";

                    dropDownVolta.DataValueField = "TVolta";

                    dropDownVolta.DataSource = dados.GetDataTable("SELECT DISTINCT Texto AS TVolta FROM dbo.Voltas").DefaultView.ToTable(true, "TVolta");

     

     

     

                }

            }

    protected void FiltroClientes_FieldEditorCreating(object sender, RadFilterFieldEditorCreatingEventArgs e)

            {

                if (e.EditorType == "RadFilterDropDownEditor")

                {

                    e.Editor = new RadFilterDropDownEditor();

                   

                }

            }

     

            protected void ApplyButton_Click(object sender, EventArgs e)

            {

                FiltroClientes.FireApplyCommand();

            }

  2. Joao
    Joao avatar
    14 posts
    Member since:
    Feb 2011

    Posted 11 Apr 2012 Link to this post

    ... Nobody??
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Vasil
    Admin
    Vasil avatar
    1547 posts

    Posted 12 Apr 2012 Link to this post

    Hello Joao,

    Could you share your C# code of "CliGrandeza_OnItemDataBound".
    It should be possible to get the FilterExpression, from the MasterTableView of your grid. Then use the filter expression to bind a DropDown in TemplateColumn.

    Page_Load on the other hand is too early for setting DataSource to your editors, since the grid has not applied it's filter expression yet.

    Kind regards,
    Vasil
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
  5. Joao
    Joao avatar
    14 posts
    Member since:
    Feb 2011

    Posted 12 Apr 2012 Link to this post

    Hi Vasil!
    Thanks for your reply.
    Maybe I didn't explain correctly what I need. The intention is to create a filter of the kind "excel like filtering" but I need to permit other operator besides the equal.
    I tried your sugestion with a template grid colunm but the result was an empty dropdown. I tried only the cration of the dropdown datasource in th OnLoad of the data grid:

    public void CliGrandeza_OnItemDataBound(object sender, GridItemEventArgs e)

    {

    GridColumn colTcliente = CliGrandeza.MasterTableView.GetColumnSafe("Tcliente");

    DataTable tbTcliente = new DataTable("TbTcliente");

    DataColumn col = new DataColumn();

    col.DataType = System.Type.GetType("System.String");

    col.ColumnName = "Tcliente";

    tbTcliente.Columns.Add(col);

    tbTcliente.Rows.Add(colTcliente.ToString());

    RadFilterDropDownEditor dropDownTipoCliente = new RadFilterDropDownEditor();

    FiltroClientes.FieldEditors.Add(dropDownTipoCliente);

    dropDownTipoCliente.FieldName = "Tcliente";

    dropDownTipoCliente.DisplayName = "Tipo de cliente";

    dropDownTipoCliente.DataTextField = "Tcliente";

    dropDownTipoCliente.DataValueField = "Tcliente";

    dropDownTipoCliente.DataSource = tbTcliente.DefaultView.ToTable(true, "Tcliente");

    }


    In this case I tried only one of the dropdowns, moving it's cration to the OnDatabound but the result was an empty drop down also.
    My problem is that I can´t correctly load the datasource that feeds the dropdown to show only the distinct elements of the Gridcolumn.
    Your help would be apreciated.
    Best regards,
    Joao
  6. Vasil
    Admin
    Vasil avatar
    1547 posts

    Posted 18 Apr 2012 Link to this post

    Hello Joao,

    If the result is empty dropdown then it's datasource is empty or it is not bounded properly. Try to use RadComboBox inside the filter template similar to this online demo:
    http://demos.telerik.com/aspnet-ajax/grid/examples/programming/filtertemplate/defaultcs.aspx
    On ItemCreated access the combo box and set it's datasource.

    Regards,
    Vasil
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017