Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

A simple database search

Hi there,

I need to do a simple search page, where a user enters in criteria via textboxes.  There are 4 values that can be used by criteria, and it needs to be searchable by any or all.  The search would be then run on a MS-SQL Server.

I can write the SQL easy enough, as it would be as simple as:
FROM Permits
field1=@param1 OR field2 = @param2 OR .... field4 = @param4

My problem is in getting the values for the parameters, and then displaying the search results.

I have the 4 textboxes, and I can get their values with a simple .text, and I imagine that the best way to display the results would be with an <asp:GridView>, but how do I tell the gridview to refresh so that it displays the records which meet the criteria, once the user has pressed the search button?
  • 4
  • 3
1 Solution
Assume you are using a datagrid, here's something that might get you started for a button click event.  Note the query you specified will only filter based on the first field=@param that returns true.  I changed it so the user can specify any field and it will filter on all of them.  When a textbox is left blank, it will not filter on the corresponding field.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      ' Declare connection and command object
        Dim conn As New SqlClient.SqlConnection("MyConnectionString")
        Dim cmd As New SqlClient.SqlCommand

        ' Add parameters to Command Object.  IF Textbox text is nothing, then
        ' set the parameter to <NULL>.
        Dim p As SqlClient.SqlParameter

        p = New SqlClient.SqlParameter("@Param1", SqlDbType.VarChar)
        p.Value = IIf(TextBox1.Text.Length = 0, DBNull.Value, TextBox1.Text)

        p = New SqlClient.SqlParameter("@Param2", SqlDbType.VarChar)
        p.Value = IIf(TextBox2.Text.Length = 0, DBNull.Value, TextBox2.Text)

        p = New SqlClient.SqlParameter("@Param3", SqlDbType.VarChar)
        p.Value = IIf(TextBox3.Text.Length = 0, DBNull.Value, TextBox3.Text)

        p = New SqlClient.SqlParameter("@Param4", SqlDbType.VarChar)
        p.Value = IIf(TextBox4.Text.Length = 0, DBNull.Value, TextBox4.Text)

        ' Set up the query.  If user did not specify something in the textbox,
        ' the corresponding parameter will have been set to null.  This query
        ' will skip the parameter when it is null, or otherwise filter by it
        ' when it is not null.
        Dim sql As String
        sql = "SELECT * FROM Permits WHERE " & _
                "(@Param1 IS NULL OR Field1 = @Param1) AND " & _
                "(@Param2 IS NULL OR Field2 = @Param2) AND " & _
                "(@Param3 IS NULL OR Field3 = @Param3) AND " & _
                "(@Param4 IS NULL OR Field4 = @Param4)"

        ' Set up the rest of the command object
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql

        ' Declare a datareader and bind to a datagrid on the page
        Dim rdr As SqlClient.SqlDataReader = cmd.ExecuteReader()
        DataGrid1.DataSource = rdr
    End Sub
lunanatAuthor Commented:
You are a genious.  The sample data I have in the database returns perfectly.

If you like, I can mark this question as answered.  Or, there is an option for more points.

It would be quite benefitial if I were able to check the expiry date (which is one of the fields in the returned data) and if the record is past it's expiry date, highlight it with red or change the font to red.

Since I can only give points to one person, that means that anyone else who answers the "bonus question" would be doing it for no points... the original question has been answered already and any answer will be given to ibost.
you can actually split points between people.  There's an option at the bottom of the page somewhere to do that.

Ok let me think about the problem for a minute...

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Ok again assuming you're using a datagrid...

I take it your query will return an ExpirationDate as part of the results.  And if today's date is greater than the ExpirationDate then you want to change the back color to red...

So what you'll do is probably use the ItemDataBound event for the datagrid:

Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

   'Check if you're looking at an item or alternating item (row) in the datagrid
   If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

      'Assume the third column has the date in it, which would be cell(2)
      If CDate(e.Item.Cells(2).Text) < DateTime.Now Then
         e.Item.Cells(2).BackColor = System.Drawing.Color.Red
         'e.Item.BackColor = System.Drawing.Color.Red (if you want the whole row highlighted)
      End If

   End If

End Sub
lunanatAuthor Commented:
I get a build error... it does not like "datagrid1.itemdatabound" in the sub's declaration

I changed 'datagrid1' to the ID of my gridview object.

If I change it to gridview1.databound then the sub's eventarg parameter needs to be changed to a system.eventargs, and then it doesn't have an .item member.

Do I need to import something?
I'm not sure how gridviews work :(

I think it uses a "rowDataBound" event instead.

Here is a sample I found that I hope you can use:

Formatting the GridView Based on the Underlying Data
In the two previous examples the GridView's formatting was specified statically. There are times, however, where you might want to alter the formatting based on the data in the GridView. For example, when listing product information you might want to draw the user's eye to products that are out of stock. One way to accomplish this would be to change the background color of those rows with a Units In Stock value of 0.

To accomplish this we need to inspect the data of each of the rows of the GridView and alter the row's BackColor property if the Units In Stock is 0. The GridView offers a RowDataBound event that fires once for each row after the row has been created and bound to the corresponding record of data from the data source control. We can create an event handler for this event that checks to see if Units In Stock is 0 and, if it is, set the BackColor property of the GridView row to Yellow.

To create an event handler for the GridView's RowDataBound event, go to the Design view, click on the GridView, and go to the Properties pane. From the Properties pane, click on the lightning bolt; this will list the GridView's events. Then, in the RowDataBound line, type in the name of the event handler you want to create (I named my event handler productsGridView_RowDataBound). Finally, enter in the following code into the event handler:

Sub productsGridView_RowDataBound(ByVal sender As Object, _
  ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        'determine the value of the UnitsInStock field
        Dim unitsInStock As Integer =  _
          Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
        If unitsInStock = 0 Then
            ' color the background of the row yellow
            e.Row.BackColor = Drawing.Color.Yellow
        End If
    End If
End Sub

The event handler starts by checking to see if we are working with a DataRow. Realize that the GridView's RowDataBound event handler fires for each of the rows being created, including the HeaderRow. However, the HeaderRow doesn't have a Units In Stock column with data associated with it, so we are only interested in working with DataRows. The UnitsInStock field from the data bound to the GridView row is obtained through a DataBinder.Eval() call, passing in the data bound to the GridView row (e.Row.DataItem) and the name of the field whose value we are interested in. Finally, a check is made to see if there are zero units in stock. If so, the BackColor property of the row is set to Yellow.
lunanatAuthor Commented:
That did exactly the trick

Thank you very much for your help.

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now