Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have managed get the search function to work but it is very chunky :(

Code:

If dropdown_sV.Value = "N" Then
        If WhereParts > 0 Then
            WhereClause = WhereClause & " AND"
        End If
        WhereClause = WhereClause & " [sV] = 'N'"
        WhereParts = WhereParts + 1
    End If

    If dropdown_sV.Value = "G" Then
        If WhereParts > 0 Then
            WhereClause = WhereClause & " AND"
        End If
        WhereClause = WhereClause & " [sV] = 'G'"
        WhereParts = WhereParts + 1
    End If

Can I make this code more efficient because I have lots of select dropdowns with the following options: N, G, O, A, R, U

It would be a nightmare to maintain my application.

share|improve this question
    
Please disregard my previous version of this question - I have managed to solve it but am now looking for a more efficient method –  Singh Jun 6 '13 at 10:52

2 Answers 2

up vote 1 down vote accepted

You could use:

If dropdown_sV.SelectedIndex > -1 Then
    If WhereClause.Length > 0 Then
        WhereClause = WhereClause & " AND"
    End If
    WhereClause = WhereClause & " [sV] = " & dropdown_sV.Value
End If

but you really should consider parameterizing your query (like so):

If dropdown_sV.SelectedIndex > -1 Then
    If WhereClause.Length > 0 Then
        WhereClause = WhereClause & " AND"
    End If
    WhereClause = WhereClause & " [sV] = @sV"
End If

After the WHERE clause is built, you merely have to associate the parameters with the value:

Dim cmd As SqlCommand = New SqlCommand(queryString, connectionString)
cmd.Parameters.Add("sV", SqlDbType.VarChar, 50).Value = dropdown_sV.Value
share|improve this answer

Yes you can use only at once the code i.e. write for every time for dropdown selection. you can reduce the code as:

If WhereParts > 0 Then
  WhereClause = WhereClause & " AND"
  End If
  string value=dropdown_sV.Value;
  WhereClause = WhereClause & " [sV] = '"+dropdown_sV.Value+"'"
  WhereParts = WhereParts + 1
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.