使用下拉列表过滤GridView

时间:2015-12-02 14:15:36

标签: c# asp.net gridview

我想使用下拉列表过滤我的GridView,以便仅显示与所选下拉项相关的结果。我发现了很多Sql Datasource的例子,但我使用的是ObjectDataSource。

这是我的GridViewDropdown

的代码
<asp:DropDownList ID="DropDownList2" runat="server" >
     <asp:ListItem  Text="Person1" Value="Name"></asp:ListItem>
     <asp:ListItem Text="Person2" Value="Name"></asp:ListItem>
     <asp:ListItem Text="Person3" Value="Name"></asp:ListItem>
     <asp:ListItem Text="Person4" Value="Name"></asp:ListItem>
</asp:DropdownList>


<asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="False"  OnPageIndexChanging="GridView1_PageIndexChanging" DataSourceID="ObjectDataSource1" >
     <PagerSettings  Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="30" />
     <PagerStyle CssClass="Pager" Font-Size="Large" Height="50px"/>
         <Columns>
            <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="" >
            <HeaderStyle Width="45%" />
            <ItemStyle HorizontalAlign="Center" Height="85px" Width="40%" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
            </asp:BoundField>
            <asp:BoundField DataField="Job" HeaderText="Department"  ReadOnly="True" SortExpression="" >
                 <ItemStyle Width="30%" HorizontalAlign="Center"  Height="85px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
            </asp:BoundField>
         </Columns>
</asp:GridView>

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Names"  SelectMethod="NamesData" />

所以我希望如果用户从下拉列表中选择Person1,GridView将只显示这些结果。任何建议都表示赞赏!

更新

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    ObjectDataSource1.FilterExpression = "Person=" + DropDownList2.SelectedValue;
    }

我已尝试过此操作但收到以下错误:

  

System.Data.SyntaxErrorException:语法错误:&#39; Person&#39;之后缺少操作数操作

1 个答案:

答案 0 :(得分:1)

为了过滤记录,显然需要在NamesData进行第一次更改,以便接受参数并返回过滤后的记录。

接下来,在ObjectDataSource控件中添加带SelectParameters标记的参数,如下所示: -

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Names"  
      SelectMethod="NamesData">
    <SelectParameters>
            <asp:ControlParameter ControlID="DropDownList2" DefaultValue=""
                 Name="personName" PropertyName="SelectedValue" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

此处,personName是您要添加到NamesData方法的参数的名称。此外,您必须相应地设置DefaultValue,以便您可以在初始页面加载中查看所有记录。

相关问题