将过滤器添加到Gridview的一个标题列

时间:2013-06-17 03:54:38

标签: asp.net vb.net gridview

我想在我的标题列[Carrier]中创建一个过滤器,这是我创建的gridview的代码:

的Index.aspx:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cr_OnSelectedIndexChanged"
                 DataSourceID="SqlDataSource1" DataTextField="CARRIER" DataValueField="CARRIER"> 
             </asp:DropDownList>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                 ConnectionString="<%$ ConnectionStrings:MybaseConnectionString %>" 
                 SelectCommand="SELECT DISTINCT [CARRIER] FROM [TABLE]">
                 </asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px">
</asp:GridView>

index.aspx.vb

Inherits System.Web.UI.Page
    Dim cx As New SqlConnection("Data Source=.\SQLEXPRESS;database=Mybase;Integrated Security=True;")
    Dim cmd As New SqlCommand
    Dim da As New SqlDataAdapter
    Dim dt As New DataTable

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
            cmd.Connection = cx
            cmd.CommandText = "select cl1, Carrier, cl2, cl3 from table"
            da = New SqlDataAdapter(cmd)
            da.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Sub

   Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

End Sub

任何人都可以帮忙! 谢谢..

4 个答案:

答案 0 :(得分:0)

拿一个文本框

<asp:TextBox runat="server" ID="txtSearch"/>  

按钮点击事件

 Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
            cmd.Connection = cx
            cmd.CommandText = "select cl1, Carrier, cl2, cl3 from table where Carrier='"+txtSearch.Text+"'"
            da = New SqlDataAdapter(cmd)
            da.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Sub

答案 1 :(得分:0)

我建议在您希望过滤的列的标题中放置一个下拉列表(在您的案例中为Carrier)。然后,您可以连接下拉列表的OnSelectedIndexChanged事件,以处理列数据的实际过滤。这个技术的一个较旧但仍然相关的例子是:

ASP.NET GridView Column Filtering

答案 2 :(得分:0)

假设Carrier是nvarchar(200)类型的字段,并且应该在用户点击Button1(在标记中不可见)之后进行过滤,方法Button1_Click的主体应该如下所示:

    Dim sql As String = "select cl1, Carrier, cl2, cl3 from table where Carrier = @Carrier"

    Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;database=Mybase;Integrated Security=True;"), _
      cmd As New SqlCommand(sql, cn)

      cmd.Parameters.Add("@Carrier", SqlDbTypes.NVarChar, 200).Value = DropDownList1.SelectedValue

      da = New SqlDataAdapter(cmd)
      da.Fill(dt)
      GridView1.DataSource = dt
      GridView1.DataBind()
    End Using

答案 3 :(得分:0)

您可能需要查看RowFilter的{​​{1}}属性。请查看this link,其中包含示例代码。