I have an asp DropDownList that is used to filter database results. One of my filters is used to check if a column is NULL or NOT NULL:
<asp:DropDownList runat="server" id="activeFilter" CssClass="form-control" AutoPostBack="false" >
<asp:ListItem selected="True" value="">-- Filter By Active/Inactive </asp:ListItem>
<asp:ListItem value="NOT NULL">Active</asp:ListItem>
<asp:ListItem value="NULL">Inactive</asp:ListItem>
</asp:DropDownList>
I then try to insert it into a parameterized query like so:
//called from another method
string query = ".... AND Status=@statusFilter ...."
SqlConnection conn = new SqlConnection(connString)
SqlCommand command = new SqlCommand(query, conn)
command.Parameters.AddWithValue("@statusFilter", statusFilter.SelectedValue);
//other stuff, make sql call
This process works for other filter values, something like
"... AND Name=@nameFilter ..."
Where nameFilter might be "John", "Tim", "Amy", etc. so I'm assuming this has something to do with the fact that NULL and NOT NULL shouldn't actually be strings. Any easy solution for this? I see I can add DBNull.Value but what about NOT NULL?
Any help would be much appreciated.
EDIT: Sorry everyone, I made a mistake in my first post - I copied the wrong query string. My query string is actually
"... AND Date_Completed IS @activeFilter ..."
I know I cant say Column=Null, so again I apologize. I'm going to run through the suggestions right now and update everyone.
EDIT 2: Okay so the issue is that you cannot treat NULL / NOT NULL as parameters. I was hoping I could use it as a parameter as I had a number of utility functions to generate the final query based on a many different filters. Ultimately, this did not work, and I needed to alter my methods and insert the entire " IS NULL " or "IS NOT NULL" directly using an If/Else block.
NULLvalue but the query doesn't work.NULLin SQL means an Unknown value. The result of comparing Unknown to Unknown is itselfUnknown. That's whyName=@nameFilterwill always fail if@nameFiltercontains a NULLNOT NULL? perhaps a bool column would be more useful in this caseifstatement to choose the right one, you can't use a parameter. Also, you should not be showing words likenullto users, that's confusing UI.IS NULLandIS NOT NULLare expressions, not values. If you want to check whetherNameis null you'll have to writeNAME IS NULL. If you want to see whether the name matches the parameter or is null itself you'll have to writeWHERE NAME IS NULL OR NAME = @nameFilter