根据输入文本框的文本动态更新GridView结果

时间:2014-06-08 23:44:05

标签: asp.net vb.net gridview sqldatasource

我想基于输入到文本框中的字符动态更新GridView的结果。我的代码目前有效但只在文本框失去焦点或用户选项卡退出文本框时触发更新。文本框的AutoPost设置为true。我有刷新SQLDataSource的代码,我只是希望在用户在文本框中输入字符时进行更新。我想这将需要客户端的行动,但不知道从哪里开始。谢谢。

MARKUP

      <asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True" ViewStateMode="Enabled"></asp:TextBox>
      <asp:Button ID="btnSearch" runat="server" Text="Search" />

      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
        <Columns>
          <asp:BoundField DataField="NameFirst" HeaderText="First Name" SortExpression="NameFirst" />
          <asp:BoundField DataField="NameLast" HeaderText="Last Name" SortExpression="NameLast" />
          <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
          <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
          <asp:BoundField DataField="State_ID" HeaderText="State" SortExpression="State_ID" />
        </Columns>
      </asp:GridView>

代码隐藏

Protected Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
GridData()
End Sub

Private Sub GridData()
    Dim conString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
    Dim sqlcon As New SqlConnection(conString)
    Dim sqlcmd As SqlCommand
    Dim da As SqlDataAdapter
    Dim dt As New System.Data.DataTable()
    Dim query As [String]

    If txtsearch.Text = "" Then
      query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] ORDER BY [NameLast], [NameFirst]"
    Else
      query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] WHERE [NameLast] LIKE N'%" + txtSearch.Text + "%' ORDER BY [NameLast], [NameFirst]"
    End If
    sqlcmd = New SqlCommand(query, sqlcon)
    sqlcon.Open()
    da = New SqlDataAdapter(sqlcmd)
    dt.Clear()
    da.Fill(dt)
    If dt.Rows.Count > 0 Then
      GridView1.DataSourceID = ""
      GridView1.DataSource = dt
      GridView1.DataBind()
    Else
      GridView1.DataBind()
    End If
    sqlcon.Close()
  End Sub

0 个答案:

没有答案