vb.net 在 DevExpress GridView 上过滤数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21258910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:30:46  来源:igfitidea点击:

Filtering Data on a DevExpress GridView

vb.netgridviewwebformsdevexpress

提问by J86

I am an MVC person, and have minimal experience with WebForms, but now I am having to add some functionality to a legacy VB.NET WebForms application.

我是一个 MVC 人,对 WebForms 的经验很少,但现在我不得不向旧的 VB.NET WebForms 应用程序添加一些功能。

So the application is using DevExpress Grids, and it displays a really long grid view on the page where one of the columns has the following:

所以应用程序使用 DevExpress Grids,它在页面上显示一个非常长的网格视图,其中一列具有以下内容:

radio actions

无线电行动

The extra functionality that I am asked to add is a filter where the user can say:

我被要求添加的额外功能是一个过滤器,用户可以在其中说:

I only want to see the rows where the on-load radio button selected is Print (or one of the other two actions).

我只想查看选择的加载单选按钮是打印(或其他两个操作之一)的行。

So I went to the bottom of the grid and created the following:

所以我去了网格的底部并创建了以下内容:

filter drop down

过滤器下拉

My thinking was, the user can come to this drop down and selected what he or she wants to filter on for radio button actions.

我的想法是,用户可以来到这个下拉菜单并选择他或她想要过滤的单选按钮操作。

DevExpress GridView Code

DevExpress GridView 代码

<dx:ASPxGridView ID="GridView1" runat="server" Theme="Office2010Blue" KeyFieldName="ID" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" Width="3200px">
    <Columns>
        <!-- Many more columns go here -->
        <dx:GridViewDataColumn Caption="" VisibleIndex="29" Name="decision" Width="150px">
            <HeaderTemplate>
                <asp:LinkButton runat="server" ID="lnkPrint" OnClick="SelectPrintAll">Print All</asp:LinkButton>
                <asp:LinkButton runat="server" ID="lnkEmail" OnClick="SelectEmailAll">Email All</asp:LinkButton>
                <asp:LinkButton runat="server" ID="lnkIgnore" OnClick="SelectIgnoreAll">Ignore All</asp:LinkButton>
            </HeaderTemplate>

            <DataItemTemplate>
                <asp:UpdatePanel runat="server" ID="upRadDecision" UpdateMode="Conditional">
                    <ContentTemplate>
                        <dx:ASPxRadioButtonList ID="radDecision" runat="server" RepeatDirection="Horizontal"
                            OnSelectedIndexChanged="StoreDecisionForRow" AutoPostBack="True" Height="15px"
                            OnDataBinding="BindDecisionRadioButton">
                            <Border BorderStyle="None"></Border>
                            <Paddings Padding="0"></Paddings>
                            <Items>
                                <dx:ListEditItem Text="Print" Value="Print" />
                                <dx:ListEditItem Text="Email" Value="Email" />
                                <dx:ListEditItem Text="Ignore" Value="Ignore" />
                            </Items>
                        </dx:ASPxRadioButtonList>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </DataItemTemplate>
            <Settings HeaderFilterMode="CheckedList"></Settings>
        </dx:GridViewDataColumn>
    </Columns>

    <!-- Stylres -->
    <Styles>
        <AlternatingRow Enabled="true" />
    </Styles>

    <!-- Settings -->
    <Settings ShowFilterRow="True" ShowFilterRowMenu="true" ShowFilterBar="Auto" ShowHeaderFilterButton="true" ShowGroupPanel="True" ShowFooter="True" />
    <SettingsBehavior AllowSelectByRowClick="False" />
    <SettingsBehavior AllowSelectSingleRowOnly="False" />
    <SettingsBehavior ProcessSelectionChangedOnServer="true" />
    <SettingsPager Mode="ShowAllRecords" />

    <GroupSummary>
        <dx:ASPxSummaryItem SummaryType="Count" />
    </GroupSummary>
</dx:ASPxGridView>

I have added a click handler to my filter button, and the code is like so:

我在过滤器按钮中添加了一个点击处理程序,代码如下:

Private Sub btnFilterDefaults_Click(sender As Object, e As EventArgs) Handles btnFilterDefaults.Click
    Dim filterOn As String = ddDefaultsFilterOption.SelectedValue
    'Code Handling the Filtering.
    GridView1.filter
    For rowIndex As Integer = 0 To GridView1.VisibleRowCount - 1
        Dim datarow = GridView1.GetDataRow(rowIndex)
        Dim radDecision As ASPxRadioButtonList = CType(GridView1.FindRowCellTemplateControl(rowIndex, Nothing, "radDecision"), ASPxRadioButtonList)
        Dim decision As String = ""

        If radDecision.Value Is Nothing then Continue For

        decision = radDecision.Value.ToString()

        If decision.Contains(filterOn) Then
            datarow.?? <<<<< no option to hide row here!!! :/
        End If
    Next
End Sub

I was hoping that when I got hold of the data row, I'd be able to hide it, but there is no such option!

我希望当我掌握数据行时,我能够隐藏它,但没有这样的选择!

回答by thetimmer

I think the issue is you're trying to apply a visible trait to a datarow. What you want to do is use GridViewRow instead. It's the presentation object. Sorry I don't have an example for you but hereis a link to msdn for it

我认为问题在于您试图将可见特征应用于数据行。您想要做的是改用 GridViewRow。它是展示对象。抱歉,我没有适合您的示例,但这里有一个指向 msdn 的链接

回答by Michael

Did you try to use HeaderFilterModefor your GridView? This function started from 12 DevExpress version, as I remember. Look at the example below, how you can enable it.

您是否尝试为您的 GridView使用HeaderFilterMode?这个功能是从 12 DevExpress 版本开始的,我记得。请看下面的示例,了解如何启用它。

    <dx:GridViewDataColumn Caption="" VisibleIndex="29" Name="decision" Width="150px">
       ...
       <Settings HeaderFilterMode="CheckedList" />
   </dx:GridViewDataColumn>

If you have older version or you need completely another functionality, you can create your own custom template for filter column. Look at the example on c# below

如果您有旧版本或完全需要其他功能,您可以为过滤器列创建自己的自定义模板。看下面c#上的例子

public class FilterLookupTemplate : ITemplate
{
    private const string FormatFilterValue = "FilterLookupTemplateValue_{0}";

    public string ClientIdLookup { get; private set; }
    public string FieldName { get; set; }
    public string DataSourceID { get; set; }
    public ASPxGridView GridView { get; set; }

    #region ITemplate Members

    /// <summary>
    /// Initialization template
    /// </summary>
    public void Init()
    {
        (GridView != null).Ensure<ArgumentException>("There didn't passed reference to grid view!");
        if (!GridView.IsClientSideAPIEnabled() || String.IsNullOrEmpty(GridView.ClientInstanceName))
        {
            GridView.ClientInstanceName = GridView.ID;
        }

        var column = GridView.Columns[FieldName] as GridViewDataColumn;
        (column != null).Ensure<ArgumentException>("There is error to get column by name!");
        column.Settings.ShowFilterRowMenu = DefaultBoolean.False;
        GridView.AutoFilterCellEditorCreate += OnAutoFilterCellEditorCreate;
        GridView.AutoFilterCellEditorInitialize += OnAutoFilterCellEditorInitialize;
        GridView.ProcessColumnAutoFilter += OnProcessColumnAutoFilter;
    }

    /// <summary>
    /// Creating filter dropdown control
    /// </summary>
    /// <param name="sender">Event sender</param>
    /// <param name="e">Event arguments</param>
    private void OnAutoFilterCellEditorCreate(object sender, ASPxGridViewEditorCreateEventArgs e)
    {
        if (e.Column.FieldName.Equals(FieldName))
        {
            var dde = new DropDownEditProperties { EnableClientSideAPI = true, DropDownWindowTemplate = this };
            e.EditorProperties = dde;
        }
    }

    /// <summary>
    /// Initializing filter dropdown control
    /// </summary>
    /// <param name="sender">Event sender</param>
    /// <param name="e">Event arguments</param>
    private void OnAutoFilterCellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
    {
        if (e.Column.FieldName.Equals(FieldName))
        {
            var editor = e.Editor as ASPxDropDownEdit;
            (editor != null).Ensure<ArgumentException>("There wasn't passed reference to the drop down editor!");
            editor.ReadOnly = true
        }
    }

    /// <summary>
    /// Processing column filtering
    /// </summary>
    /// <param name="sender">Event sender</param>
    /// <param name="e">Event arguments</param>
    private void OnProcessColumnAutoFilter(object sender, ASPxGridViewAutoFilterEventArgs e)
    {
        var session = GridView.Page.Session;
        if (e.Kind == GridViewAutoFilterEventKind.CreateCriteria)
        {
            session[String.Format(FormatFilterValue, e.Column.FieldName)] = e.Value;
            if (e.Column.FieldName.Equals(FieldName) && !String.IsNullOrEmpty(e.Value))
            {
                var values = e.Value.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                if (values.Length > 0)
                {
                    var action = new Func<string, string, FunctionOperator>((name, value) =>
                              new FunctionOperator(FunctionOperatorType.Contains, new OperandProperty(name), new OperandValue(value)));
                    if (values.Length > 1)
                    {
                        var group = new GroupOperator(GroupOperatorType.Or);
                        group.Operands.AddRange(values.Select(v => action(e.Column.FieldName, v)).ToArray());
                        e.Criteria = group;
                    }
                    else
                    {
                        e.Criteria = action(e.Column.FieldName, values[0]);
                    }
                }
            }
        }
        else
        {
            if (session[String.Format(FormatFilterValue, e.Column.FieldName)] != null)
            {
                e.Value = session[String.Format(FormatFilterValue, e.Column.FieldName)].ToString();
            }
        }
    }

    /// <summary>
    /// Rendering loolup template controls
    /// </summary>
    /// <param name="container">Container of date range template</param>
    public void InstantiateIn(Control container)
    {
        (GridView != null).Ensure<ArgumentException>("There didn't passed reference to grid view!");
        var table = new Table { Width = new Unit(200, UnitType.Pixel) };
        container.Controls.Add(table);

        var row = new TableRow();
        table.Rows.Add(row);

        var cell = new TableCell();
        row.Cells.Add(cell);

        var lbl = new ASPxLabel { ID = "lblSelect", Text = MessageResources.FilterLookupTemplate_SelectLabelText };
        cell.Controls.Add(lbl);

        cell = new TableCell();
        row.Cells.Add(cell);
        var lookup = new ASPxGridLookup
                         {
                             ID = GridView.ID + "lookupValues",
                             EnableClientSideAPI = true,
                             Width = new Unit(100, UnitType.Percentage),
                             SelectionMode = GridLookupSelectionMode.Multiple
                         };
        lookup.GridView.Width = new Unit(100, UnitType.Percentage);
        lookup.GridView.DataSourceID = DataSourceID;
        lookup.GridView.KeyFieldName = "id";
        lookup.GridView.Columns.Add(new GridViewCommandColumn { ShowSelectCheckbox = true, AllowDragDrop = DefaultBoolean.False });
        var nameColumn = new GridViewDataTextColumn { FieldName = "name" };
        nameColumn.Settings.AllowDragDrop = DefaultBoolean.False;
        nameColumn.Settings.AllowGroup = DefaultBoolean.False;
        nameColumn.Settings.AllowHeaderFilter = DefaultBoolean.False;
        nameColumn.Settings.AllowSort = DefaultBoolean.False;
        lookup.GridView.Columns.Add(nameColumn);
        lookup.EnableClientSideAPI = true;
        cell.Controls.Add(lookup);
        ClientIdLookup = lookup.ClientID;
        row = new TableRow();
        table.Rows.Add(row);
        cell = new TableCell { ColumnSpan = 2 };
        row.Cells.Add(cell);

        var lnk = new ASPxHyperLink { Text = MessageResources.FilterLookupTemplate_ApplyLinkText, NavigateUrl = "#" };
        lnk.ClientSideEvents.Click =
            String.Format("function (s, e) {{ {0}.HideDropDown(); ApplyLookupFilter({0}, {1}, '{2}', {3}); }}",
                          container.NamingContainer.NamingContainer.ClientID,
                          GridView.ClientInstanceName,
                          FieldName,
                          ClientIdLookup);
        cell.Controls.Add(lnk);
        container.Controls.Add(table);
    }

    #endregion
}

and then register it for your grid view. ReportsCustomerDataSource is a LINQ data source control.

然后为您的网格视图注册它。ReportsCustomerDataSource 是一个 LINQ 数据源控件。

public partial class YourPage: Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        new FilterLookupTemplate { FieldName = "ReportCustomers", DataSourceID = ReportsCustomerDataSource.ID, GridView = _gridView }.Init();
    }
}

On the form it will be look like that

在表格上它看起来像那样

enter image description here

在此处输入图片说明