2015-12-02 72 views
0

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

这是代码为我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控件将只显示那些结果。任何建议表示赞赏!

UPDATE

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

我已经试过,但我得到了以下错误:

System.Data.SyntaxErrorException: Syntax error: Missing operand after 'Person' operator.

+1

[ObjectDataSource](https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.filterexpression(v = vs.110).aspx)有一个“FilterExpression”字符串属性。你可以简单地在'DropDownList'的'SelectedIndexChanged'事件中设置它吗?就像'ods.FilterExpression =“Name =”+ ddl.SelectedValue;' – sab669

+0

是的我试过了,但似乎没有发生任何事 – MariaL

+0

分享你的实际代码。 ASP标记是伟大的,所有人都知道页面的样子,但没有看到你如何配置过滤器表达式,更新网格等我们在这里黑暗中 – sab669

回答

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,以便您可以在初始页面加载中查看所有记录。