Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


A simple database search

Posted on 2006-07-11
Medium Priority
Last Modified: 2008-01-09
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?
Question by:lunanat
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 10

Expert Comment

ID: 17083154
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

Author Comment

ID: 17085750
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.
LVL 10

Expert Comment

ID: 17085813
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...
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 10

Expert Comment

ID: 17086084
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

Author Comment

ID: 17091250
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?
LVL 10

Accepted Solution

ibost earned 800 total points
ID: 17091617
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.

Author Comment

ID: 17092383
That did exactly the trick

Thank you very much for your help.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question