smith68349
asked on
sqldatareader code problem.
I am getting the following error when I run my asp.net 1.1 in vb.net application:
Prepared statement '(@apartmentID int,@rentrange varchar(13),@bedrooms varchar(13),@' expects parameter @offstreet, which was not supplied.
Here is the code I am using:
Dim apartmentid As Integer
Dim rentrange, bedrooms, bathrooms, pets, smoking, airconditioning, clubhouse, offstreet, fireplace, dishwasher, secureentry, allelectric, wheelchair, laundryroom, washerhookup, sqlsubstrrentrange, sqlsubstrbathrooms, sqlsubstrbedrooms, sqlsubstrsmoking, sqlsubstrpets, sqlsubstrairconditioning, sqlsubstrclubhouse, sqlsubstroffstreet, sqlsubstrfireplace, sqlsubstrdishwasher, sqlsubstrsecureentry, sqlsubstrallelectric, sqlsubstrwheelchair, sqlsubstrlaundryroom, sqlsubstrwasherhookup As String
rentrange = Request.QueryString("rentr ange")
bathrooms = Request.QueryString("bathr ooms")
bedrooms = Request.QueryString("bedro oms")
smoking = Request.QueryString("smoki ng")
pets = Request.QueryString("pets" )
airconditioning = Request.QueryString("Centr al Air Conditioning")
clubhouse = Request.QueryString("clubh ouse")
offstreet = Request.QueryString("Offst reet Parking")
fireplace = Request.QueryString("firep lace")
dishwasher = Request.QueryString("dishw asher")
secureentry = Request.QueryString("Secur e Entry")
allelectric = Request.QueryString("All Electric")
wheelchair = Request.QueryString("wheel chair access")
laundryroom = Request.QueryString("laund ry room")
washerhookup = Request.QueryString("Washe r/Dryer Hookup")
If (rentrange = "No Preference") And (bathrooms = "No Preference") And (bedrooms = "No Preference") And (smoking = "No Preference") And (pets = "No Preference") Then
smoking = "yes"
End If
If rentrange = "No Preference" Then
sqlsubstrrentrange = ""
If bedrooms = "no preference" Then
sqlsubstrbedrooms = ""
If bathrooms = "no preference" Then
sqlsubstrbathrooms = ""
If pets = "no preference" Then
sqlsubstrpets = ""
If smoking = "no preference" Then
sqlsubstrsmoking = ""
Else
sqlsubstrsmoking = "where(smoking=@smoking)"
End If
Else
sqlsubstrpets = "where (pets=@pets)"
End If
Else
sqlsubstrrentrange = "Where (Case WHEN rent <= 400 then 'Less than $400' WHEN rent < 500 then rent '$401-$499' WHEN rent < 600 then rent '$500-$599' WHEN rent < 700 then rent '$600-$700' else '$700 and more' END = @rentrange)"
End If
Else
sqlsubstrbedrooms = "where(bedrooms=@bedrooms) "
End If
Else
sqlsubstrbathrooms = "where (bathrooms=@bathrooms)"
If sqlsubstrrentrange = "No Preference" Then
sqlsubstrrentrange = ""
Else
sqlsubstrrentrange = "AND(Case WHEN rent <= 400 then 'Less than $400' WHEN rent < 500 then rent '$401-$499' WHEN rent < 600 then rent '$500-$599' WHEN rent < 700 then rent '$600-$700' else '$700 and more'END = @rentrange"
End If
If bedrooms = "Yes" Then
sqlsubstrbedrooms = "AND (bedrooms=@bedrooms)"
Else
sqlsubstrbedrooms = ""
End If
If bathrooms = "Yes" Then
sqlsubstrbathrooms = "AND (Bathrooms=@Bathrooms)"
Else
sqlsubstrbathrooms = ""
If smoking = "Yes" Then
sqlsubstrsmoking = "AND (smoking=@smoking)"
Else
sqlsubstrsmoking = ""
If pets = "Yes" Then
sqlsubstrpets = "AND (pets=@pets)"
Else
sqlsubstrpets = ""
If airconditioning = "Yes" Then
sqlsubstrairconditioning = "AND (airconditioning =@airconditioning)"
Else
sqlsubstrairconditioning = ""
If clubhouse = "Yes" Then
sqlsubstrclubhouse = "AND (clubhouse= @clubhouse)"
Else
sqlsubstrclubhouse = ""
End If
If offstreet = "yes" Then
sqlsubstroffstreet = "AND (offstreet=@offstreet)"
Else
sqlsubstroffstreet = ""
If fireplace = "Yes" Then
sqlsubstrfireplace = "AND (fireplace=@fireplace)"
Else
sqlsubstrfireplace = ""
If dishwasher = "Yes" Then
sqlsubstrdishwasher = "AND (dishwasher=@dishwasher)"
Else
sqlsubstrdishwasher = ""
If secureentry = "Yes" Then
sqlsubstrsecureentry = "AND (secureentry=@secureentry) "
Else
sqlsubstrsecureentry = ""
If allelectric = "yes" Then
sqlsubstrallelectric = "AND(allelectric=@allelect ric)"
Else
sqlsubstrallelectric = ""
If wheelchair = "yes" Then
sqlsubstrwheelchair = "AND (wheelchair=@wheelchair)"
Else
sqlsubstrwheelchair = ""
If laundryroom = "yes" Then
sqlsubstrlaundryroom = "AND (laundryroom=@laundryroom) "
Else
sqlsubstrlaundryroom = ""
If washerhookup = "yes" Then
sqlsubstrwasherhookup = "AND(washerhookup=@washerh ookup)"
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
myconnection = New SqlConnection("****")
myconnection.Open()
mycommand = New SqlCommand("SELECT image, rent, address, link, proppage FROM apartments " & sqlsubstrrentrange & sqlsubstrbathrooms & sqlsubstrbedrooms & sqlsubstrpets & sqlsubstrsmoking & sqlsubstrclubhouse & sqlsubstrairconditioning & sqlsubstroffstreet & sqlsubstrfireplace & sqlsubstrdishwasher & sqlsubstrsecureentry & sqlsubstrallelectric & sqlsubstrwheelchair & sqlsubstrlaundryroom & sqlsubstrwasherhookup, myconnection)
mycommand.Parameters.Add(N ew SqlParameter("@apartmentID ", SqlDbType.Int))
mycommand.Parameters("@apa rtmentID") .Value = apartmentid
mycommand.Parameters.Add(N ew SqlParameter("@rentrange", SqlDbType.VarChar))
mycommand.Parameters("@ren trange").V alue = rentrange
mycommand.Parameters.Add(N ew SqlParameter("@bedrooms", SqlDbType.VarChar))
mycommand.Parameters("@bed rooms").Va lue = bedrooms
mycommand.Parameters.Add(N ew SqlParameter("@offstreet", SqlDbType.VarChar))
mycommand.Parameters("@off street").V alue = offstreet
mycommand.Parameters.Add(N ew SqlParameter("@bathrooms", SqlDbType.VarChar))
mycommand.Parameters("@bat hrooms").V alue = bathrooms
mycommand.Parameters.Add(N ew SqlParameter("@smoking", SqlDbType.VarChar))
mycommand.Parameters("@smo king").Val ue = smoking
mycommand.Parameters.Add(N ew SqlParameter("@pets", SqlDbType.VarChar))
mycommand.Parameters("@pet s").Value = pets
mycommand.Parameters.Add(N ew SqlParameter("@airconditio ning", SqlDbType.VarChar))
mycommand.Parameters("@air conditioni ng").Value = airconditioning
mycommand.Parameters.Add(N ew SqlParameter("@clubhouse", SqlDbType.VarChar))
mycommand.Parameters("@clu bhouse").V alue = clubhouse
mycommand.Parameters.Add(N ew SqlParameter("@fireplace", SqlDbType.VarChar))
mycommand.Parameters("@fir eplace").V alue = fireplace
mycommand.Parameters.Add(N ew SqlParameter("@dishwasher" , SqlDbType.VarChar))
mycommand.Parameters("@dis hwasher"). Value = dishwasher
mycommand.Parameters.Add(N ew SqlParameter("@secureentry ", SqlDbType.VarChar))
mycommand.Parameters("@sec ureentry") .Value = secureentry
mycommand.Parameters.Add(N ew SqlParameter("@allelectric ", SqlDbType.VarChar))
mycommand.Parameters("@all electric") .Value = allelectric
mycommand.Parameters.Add(N ew SqlParameter("@wheelchair" , SqlDbType.VarChar))
mycommand.Parameters("@whe elchair"). Value = wheelchair
mycommand.Parameters.Add(N ew SqlParameter("@laundryroom ", SqlDbType.VarChar))
mycommand.Parameters("@lau ndryroom") .Value = laundryroom
mycommand.Parameters.Add(N ew SqlParameter("@washerhooku p", SqlDbType.VarChar))
mycommand.Parameters("@was herhookup" ).Value = washerhookup
Dim reader As SqlDataReader
reader = mycommand.ExecuteReader()
'show results in grid
If reader.HasRows() Then
lblresults.Visible = False
DataList1.DataSource = reader
DataList1.DataBind()
This code is meant to take values from a series of radiobuttonlists and one checkboxlist from "apartments.aspx" and pass them through a sql database. I appreciate any help you can give me on this.
Jerry Smith
Prepared statement '(@apartmentID int,@rentrange varchar(13),@bedrooms varchar(13),@' expects parameter @offstreet, which was not supplied.
Here is the code I am using:
Dim apartmentid As Integer
Dim rentrange, bedrooms, bathrooms, pets, smoking, airconditioning, clubhouse, offstreet, fireplace, dishwasher, secureentry, allelectric, wheelchair, laundryroom, washerhookup, sqlsubstrrentrange, sqlsubstrbathrooms, sqlsubstrbedrooms, sqlsubstrsmoking, sqlsubstrpets, sqlsubstrairconditioning, sqlsubstrclubhouse, sqlsubstroffstreet, sqlsubstrfireplace, sqlsubstrdishwasher, sqlsubstrsecureentry, sqlsubstrallelectric, sqlsubstrwheelchair, sqlsubstrlaundryroom, sqlsubstrwasherhookup As String
rentrange = Request.QueryString("rentr
bathrooms = Request.QueryString("bathr
bedrooms = Request.QueryString("bedro
smoking = Request.QueryString("smoki
pets = Request.QueryString("pets"
airconditioning = Request.QueryString("Centr
clubhouse = Request.QueryString("clubh
offstreet = Request.QueryString("Offst
fireplace = Request.QueryString("firep
dishwasher = Request.QueryString("dishw
secureentry = Request.QueryString("Secur
allelectric = Request.QueryString("All Electric")
wheelchair = Request.QueryString("wheel
laundryroom = Request.QueryString("laund
washerhookup = Request.QueryString("Washe
If (rentrange = "No Preference") And (bathrooms = "No Preference") And (bedrooms = "No Preference") And (smoking = "No Preference") And (pets = "No Preference") Then
smoking = "yes"
End If
If rentrange = "No Preference" Then
sqlsubstrrentrange = ""
If bedrooms = "no preference" Then
sqlsubstrbedrooms = ""
If bathrooms = "no preference" Then
sqlsubstrbathrooms = ""
If pets = "no preference" Then
sqlsubstrpets = ""
If smoking = "no preference" Then
sqlsubstrsmoking = ""
Else
sqlsubstrsmoking = "where(smoking=@smoking)"
End If
Else
sqlsubstrpets = "where (pets=@pets)"
End If
Else
sqlsubstrrentrange = "Where (Case WHEN rent <= 400 then 'Less than $400' WHEN rent < 500 then rent '$401-$499' WHEN rent < 600 then rent '$500-$599' WHEN rent < 700 then rent '$600-$700' else '$700 and more' END = @rentrange)"
End If
Else
sqlsubstrbedrooms = "where(bedrooms=@bedrooms)
End If
Else
sqlsubstrbathrooms = "where (bathrooms=@bathrooms)"
If sqlsubstrrentrange = "No Preference" Then
sqlsubstrrentrange = ""
Else
sqlsubstrrentrange = "AND(Case WHEN rent <= 400 then 'Less than $400' WHEN rent < 500 then rent '$401-$499' WHEN rent < 600 then rent '$500-$599' WHEN rent < 700 then rent '$600-$700' else '$700 and more'END = @rentrange"
End If
If bedrooms = "Yes" Then
sqlsubstrbedrooms = "AND (bedrooms=@bedrooms)"
Else
sqlsubstrbedrooms = ""
End If
If bathrooms = "Yes" Then
sqlsubstrbathrooms = "AND (Bathrooms=@Bathrooms)"
Else
sqlsubstrbathrooms = ""
If smoking = "Yes" Then
sqlsubstrsmoking = "AND (smoking=@smoking)"
Else
sqlsubstrsmoking = ""
If pets = "Yes" Then
sqlsubstrpets = "AND (pets=@pets)"
Else
sqlsubstrpets = ""
If airconditioning = "Yes" Then
sqlsubstrairconditioning = "AND (airconditioning =@airconditioning)"
Else
sqlsubstrairconditioning = ""
If clubhouse = "Yes" Then
sqlsubstrclubhouse = "AND (clubhouse= @clubhouse)"
Else
sqlsubstrclubhouse = ""
End If
If offstreet = "yes" Then
sqlsubstroffstreet = "AND (offstreet=@offstreet)"
Else
sqlsubstroffstreet = ""
If fireplace = "Yes" Then
sqlsubstrfireplace = "AND (fireplace=@fireplace)"
Else
sqlsubstrfireplace = ""
If dishwasher = "Yes" Then
sqlsubstrdishwasher = "AND (dishwasher=@dishwasher)"
Else
sqlsubstrdishwasher = ""
If secureentry = "Yes" Then
sqlsubstrsecureentry = "AND (secureentry=@secureentry)
Else
sqlsubstrsecureentry = ""
If allelectric = "yes" Then
sqlsubstrallelectric = "AND(allelectric=@allelect
Else
sqlsubstrallelectric = ""
If wheelchair = "yes" Then
sqlsubstrwheelchair = "AND (wheelchair=@wheelchair)"
Else
sqlsubstrwheelchair = ""
If laundryroom = "yes" Then
sqlsubstrlaundryroom = "AND (laundryroom=@laundryroom)
Else
sqlsubstrlaundryroom = ""
If washerhookup = "yes" Then
sqlsubstrwasherhookup = "AND(washerhookup=@washerh
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
myconnection = New SqlConnection("****")
myconnection.Open()
mycommand = New SqlCommand("SELECT image, rent, address, link, proppage FROM apartments " & sqlsubstrrentrange & sqlsubstrbathrooms & sqlsubstrbedrooms & sqlsubstrpets & sqlsubstrsmoking & sqlsubstrclubhouse & sqlsubstrairconditioning & sqlsubstroffstreet & sqlsubstrfireplace & sqlsubstrdishwasher & sqlsubstrsecureentry & sqlsubstrallelectric & sqlsubstrwheelchair & sqlsubstrlaundryroom & sqlsubstrwasherhookup, myconnection)
mycommand.Parameters.Add(N
mycommand.Parameters("@apa
mycommand.Parameters.Add(N
mycommand.Parameters("@ren
mycommand.Parameters.Add(N
mycommand.Parameters("@bed
mycommand.Parameters.Add(N
mycommand.Parameters("@off
mycommand.Parameters.Add(N
mycommand.Parameters("@bat
mycommand.Parameters.Add(N
mycommand.Parameters("@smo
mycommand.Parameters.Add(N
mycommand.Parameters("@pet
mycommand.Parameters.Add(N
mycommand.Parameters("@air
mycommand.Parameters.Add(N
mycommand.Parameters("@clu
mycommand.Parameters.Add(N
mycommand.Parameters("@fir
mycommand.Parameters.Add(N
mycommand.Parameters("@dis
mycommand.Parameters.Add(N
mycommand.Parameters("@sec
mycommand.Parameters.Add(N
mycommand.Parameters("@all
mycommand.Parameters.Add(N
mycommand.Parameters("@whe
mycommand.Parameters.Add(N
mycommand.Parameters("@lau
mycommand.Parameters.Add(N
mycommand.Parameters("@was
Dim reader As SqlDataReader
reader = mycommand.ExecuteReader()
'show results in grid
If reader.HasRows() Then
lblresults.Visible = False
DataList1.DataSource = reader
DataList1.DataBind()
This code is meant to take values from a series of radiobuttonlists and one checkboxlist from "apartments.aspx" and pass them through a sql database. I appreciate any help you can give me on this.
Jerry Smith
ASKER
I would love to create a stored procedure for this as I think it will be a bit more efficient but I wouldn't know how to refer to it in my code. I haven't been able to figure that part out.
Also, another question... I currently have the choices set as varchar. Would it be better to set them as int? How would I get the rentrange set in my stored procedure? And finally, refer to it in my sqldatareader?
Also, another question... I currently have the choices set as varchar. Would it be better to set them as int? How would I get the rentrange set in my stored procedure? And finally, refer to it in my sqldatareader?
Stored procedures are really easy to refer to in code. You would just set the CommandType property of the SqlCommand to CommandType.StoredProcedur e. You'd add all the parameters the same way then execute it. The benefit is you could have all the logic to build your select statement inside the stored proc.
Dim myCmd As New SqlClient.SqlCommand
myCmd.CommandType = CommandType.StoredProcedur e
myCmd.CommandText = "MyProcedureName"
myCmd.Parameters.Add("@Par am1", SqlDbType.Bit)
myCmd.Parameters("@Param1" ).Value = SomeValue
myCmd.Parameters.Add("@Par am2", SqlDbType.Int)
myCmd.Parameters("@Param2" ).Value = SomeOtherValue
As for the bulk of your params such as "pets", "clubhouse", "fireplace", i assume these are either yes or no. So they would be good to define in your database as the sqltype "bit" (1 or 0). For things like bathrooms and bedrooms, define those as INTs in the db.
For rent range, what I think would be better is that you store the monthly rent for each unit in the db as an int type. Then you could have two textboxes where the use could type in the minimum and maximum rent values (or you could use drop down lists with some predefined values). If they type in nothing then you have a case where you'll either want default values in the textboxes or you could pass nulls to the stored proc
Then your select statement could say
where
rent >= @MinimumRent
and rent <= @MaximumRent
this assumes they always type something in or the min textbox defaults to 0 and the max textbox defaults to something like 5000
If you wanted to pass nulls to the proc
where
(@MinimumRent is null or rent >= @MinimumRent)
and (@MaximumRent is null or rent <= @MaximumRent)
Dim myCmd As New SqlClient.SqlCommand
myCmd.CommandType = CommandType.StoredProcedur
myCmd.CommandText = "MyProcedureName"
myCmd.Parameters.Add("@Par
myCmd.Parameters("@Param1"
myCmd.Parameters.Add("@Par
myCmd.Parameters("@Param2"
As for the bulk of your params such as "pets", "clubhouse", "fireplace", i assume these are either yes or no. So they would be good to define in your database as the sqltype "bit" (1 or 0). For things like bathrooms and bedrooms, define those as INTs in the db.
For rent range, what I think would be better is that you store the monthly rent for each unit in the db as an int type. Then you could have two textboxes where the use could type in the minimum and maximum rent values (or you could use drop down lists with some predefined values). If they type in nothing then you have a case where you'll either want default values in the textboxes or you could pass nulls to the stored proc
Then your select statement could say
where
rent >= @MinimumRent
and rent <= @MaximumRent
this assumes they always type something in or the min textbox defaults to 0 and the max textbox defaults to something like 5000
If you wanted to pass nulls to the proc
where
(@MinimumRent is null or rent >= @MinimumRent)
and (@MaximumRent is null or rent <= @MaximumRent)
I'm not too sure how you have everything laid out but to make the sp easier I'll assume you have textboxes for min and max rent:
<asp:TextBox id="tbxMinimumRent" runat="server"></asp:TextB ox>
<asp:TextBox id="tbxMaximumRent" runat="server"></asp:TextB ox>
And other stuff where user selects would be drop down lists like:
<asp:dropdownlist id="ddlBathrooms" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:dropdownlist>
<asp:dropdownlist id="ddlFireplace" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListIte m>
<asp:ListItem Value="0">No</asp:ListItem >
</asp:dropdownlist>
So notice that when user has no preference, I have set the list item value to a flag of -1.
Now you'll have some event, probably a button click where you can fire off a call to your stored proc:
Dim cmd As New SqlClient.SqlCommand
Dim conn As New SqlClient.SqlConnection("* **")
cmd.CommandType = CommandType.StoredProcedur e
cmd.CommandText = "GetApartmentList"
cmd.Connection = conn
Dim p As SqlClient.SqlParameter
p = New SqlClient.SqlParameter("@M inimumRent ", SqlDbType.Int)
p.Value = IIf(tbxMinimumRent.Text.Le ngth = 0, DBNull.Value, tbxMinimumRent.Text)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@M aximumRent ", SqlDbType.Int)
p.Value = IIf(tbxMaximumRent.Text.Le ngth = 0, DBNull.Value, tbxMaximumRent.Text)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@B athrooms", SqlDbType.Int)
p.Value = IIf(ddlBathrooms.SelectedV alue = -1, DBNull.Value, ddlBathrooms.SelectedValue )
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@F ireplace", SqlDbType.Bit)
p.Value = IIf(ddlFireplace.SelectedV alue = -1, DBNull.Value, ddlFireplace.SelectedValue )
cmd.Parameters.Add(p)
'Add rest of the paramter values in the same way
Dim rdr As SqlClient.SqlDataReader
conn.Open()
rdr = cmd.ExecuteReader()
'Bind to a datagrid or do something with the reader here
rdr.Close()
conn.Close()
Now for the stored proc itself, it would be created by using something like this:
create procedure GetApartmentList
@MinimumRent int = null -- saying '= null' means it will default to null value if not specified
, @MaximumRent int = null
, @Bathrooms int = null
, @Fireplace bit = null
-- etc... put in rest of parameters
as
select *
from ApartmentTable
where
(@MinimumRent is null or ApartmentTable.Rent >= @MinimumRent)
and (@MaximumRent is null or ApartmentTable.Rent <= @MaximumRent)
and (@Bathrooms is null or ApartmentTable.Bathrooms >= @Bathrooms)
and (@Fireplace is null or ApartmentTable.Fireplace = @Fireplace)
-- etc etc
GO
I hope that helps - didn't actually test this code ;-)
-Ian
<asp:TextBox id="tbxMinimumRent" runat="server"></asp:TextB
<asp:TextBox id="tbxMaximumRent" runat="server"></asp:TextB
And other stuff where user selects would be drop down lists like:
<asp:dropdownlist id="ddlBathrooms" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:dropdownlist>
<asp:dropdownlist id="ddlFireplace" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListIte
<asp:ListItem Value="0">No</asp:ListItem
</asp:dropdownlist>
So notice that when user has no preference, I have set the list item value to a flag of -1.
Now you'll have some event, probably a button click where you can fire off a call to your stored proc:
Dim cmd As New SqlClient.SqlCommand
Dim conn As New SqlClient.SqlConnection("*
cmd.CommandType = CommandType.StoredProcedur
cmd.CommandText = "GetApartmentList"
cmd.Connection = conn
Dim p As SqlClient.SqlParameter
p = New SqlClient.SqlParameter("@M
p.Value = IIf(tbxMinimumRent.Text.Le
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@M
p.Value = IIf(tbxMaximumRent.Text.Le
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@B
p.Value = IIf(ddlBathrooms.SelectedV
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@F
p.Value = IIf(ddlFireplace.SelectedV
cmd.Parameters.Add(p)
'Add rest of the paramter values in the same way
Dim rdr As SqlClient.SqlDataReader
conn.Open()
rdr = cmd.ExecuteReader()
'Bind to a datagrid or do something with the reader here
rdr.Close()
conn.Close()
Now for the stored proc itself, it would be created by using something like this:
create procedure GetApartmentList
@MinimumRent int = null -- saying '= null' means it will default to null value if not specified
, @MaximumRent int = null
, @Bathrooms int = null
, @Fireplace bit = null
-- etc... put in rest of parameters
as
select *
from ApartmentTable
where
(@MinimumRent is null or ApartmentTable.Rent >= @MinimumRent)
and (@MaximumRent is null or ApartmentTable.Rent <= @MaximumRent)
and (@Bathrooms is null or ApartmentTable.Bathrooms >= @Bathrooms)
and (@Fireplace is null or ApartmentTable.Fireplace = @Fireplace)
-- etc etc
GO
I hope that helps - didn't actually test this code ;-)
-Ian
ASKER
I have been using a radiobuttonlist for rent, bathroom, bedrooms, smoking, and pets. I agree it makes a lot of sense to use a textbox for the rent as the sp will be much easier to create that way. However, I have been using a checkbox list for the features such as air conditioning, clubhouse, wheelchair access, etc. I could use that same philosophy for the radiobuttonlists and the one checkbox list couldn't I?
Also, in my select statement on the code I started out with, I was hoping to get the image, true rent amount, address of the property, and a link to a page that will tell more about the property and download an application. I am familiar with that part but the request.querystring and response.redirect are new to me.
I appreciate the help I am getting on this matter. I am about an hour away from an epiphany. :)
Jerry
Also, in my select statement on the code I started out with, I was hoping to get the image, true rent amount, address of the property, and a link to a page that will tell more about the property and download an application. I am familiar with that part but the request.querystring and response.redirect are new to me.
I appreciate the help I am getting on this matter. I am about an hour away from an epiphany. :)
Jerry
ASKER
I tried to create the stored procedure based on the information you gave me. It is giving me syntax errors as well as telling me to "declare variables". I'm even more lost now than I was before I sat down tonight. :)
Ok let's forget about the stored proc for now and just build the query inline. I sort of got sidetracked and forgot you were passing on the querystring (I had envisioned all the controls at the top and a datagrid on the same page)
Ok so let's say you have webform1 which is where the user selects all the stuff and then you response.redirect to webform2 and pass a querystring. Webform2 is where you build and run the query.
Now on webform1, you'll have some textboxes for min and max rent. If the user leaves them blank we know they have no preference about rent. This assumes the database table for your apartments stores and integer value for how much the rent is for each unit, for instance 500, 999, 650, etc:
<asp:TextBox id="tbxMinRent" runat="server"></asp:TextB ox>
<asp:TextBox id="tbxMaxRent" runat="server"></asp:TextB ox>
You also have radio button lists, say for things like # of bathrooms, bedrooms, etc. By default we will have the "No Preference" option selected and a value of -1 which is a flag indicating the user does not care how many the apartment has:
<asp:RadioButtonList id="rblBathrooms" runat="server">
<asp:ListItem Selected="True" Value="-1">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList id="rblBedrooms" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
Finally, you have a checkbox list indicating yes or no for some other amenities. Generally, if user checks the box that would mean they do want that amenity (for instance, a fireplace). However if user does not check the box it probably means they don't care, (for instance user does not specifically want a fireplace or clubhouse, but probably wouldn't be opposed if the unit actually came with it). Perhaps a distinction could be made for Smoking, however, where if the user selects smoking they want a smoking unit and if they do not check smoking then they probably do NOT want a unit that allows smoking (or has been smoked in):
<asp:CheckBoxList id="cblAmenities" runat="server">
<asp:ListItem Value="Fireplace">Fireplac e</asp:Lis tItem>
<asp:ListItem Value="Smoking">Smoking</a sp:ListIte m>
<asp:ListItem Value="Clubhouse">Clubhous e</asp:Lis tItem>
</asp:CheckBoxList>
Finally, on webform1 there is a button that the user clicks to run the search. This button will validate the page and redirect to webform2 after forming the querystring:
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button >
In the code behind for webform1, you will have a function for the button click. First we will see if user typed anything in the rent textboxes. If user typed nothing we will assign the -1 (no preference) flag. Otherwise we assign whatever value user typed in. Next we assign the values for bathrooms and bedrooms. Again if "no preference" was selected, the -1 flag gets assigned. Finally, we'll declare some booleans for the checkboxlist (which i called cblAmenities). Then we loop through the listitems and check each one for whether it is true or false, then assign as appropriate. Lastly, we response.redirect to webform2 and formulate the querystring that will get passed along:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim minRent As Integer = IIf(tbxMinRent.Text.Length = 0, -1, tbxMinRent.Text)
Dim maxRent As Integer = IIf(tbxMaxRent.Text.Length = 0, -1, tbxMaxRent.Text)
Dim bathrooms As Integer = rblBathrooms.SelectedValue
Dim bedrooms As Integer = rblBedrooms.SelectedValue
'Check box list stuff
Dim Fireplace As Boolean
Dim Clubhouse As Boolean
Dim Smoking As Boolean
Dim i As Integer 'Counter for looping
For i = 0 To cblAmenities.Items.Count - 1
If cblAmenities.Items(i).Text = "Fireplace" Then
Fireplace = cblAmenities.Items(i).Sele cted
End If
If cblAmenities.Items(i).Text = "Clubhouse" Then
Clubhouse = cblAmenities.Items(i).Sele cted
End If
If cblAmenities.Items(i).Text = "Smoking" Then
Smoking = cblAmenities.Items(i).Sele cted
End If
Next
Response.Redirect("webform 2.aspx?" & _
"MinRent=" & minRent.ToString() & _
"&MaxRent=" & maxRent.ToString() & _
"&Bathrooms=" & bathrooms.ToString() & _
"&Bedrooms=" & bedrooms.ToString() & _
"&Fireplace=" & Fireplace.ToString() & _
"&Clubhouse=" & Clubhouse.ToString() & _
"&Smoking=" & Smoking.ToString())
End Sub
On to webform2 where we run the query. I added a basic datagrid called DataGrid1 to this page.
<asp:datagrid id="DataGrid1" runat="server"></asp:datag rid>
In the code-behind for webform2, I have the Page_Load function. First is to get the values off the querystring. Next I declare the sql objects I need. Instead of a stored procedure, I am just formulating the select statement in this function. Note for most of the parameters, if the user has "no preference" i assign it a value of NULL (by using dbnull.value). In the actual select statement's "where" clause, I go through each filter item and check - Is the variable null? That means the user had no preference so I move on to the next item. If the variable is not null, the user must have a preference so I check that the record meets the criteria. Finally I open my connection, execute the datareader, and then bind the results to my basic datagrid.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get values from querystring
Dim minRent As Integer = CType(Request.QueryString( "MinRent") , Integer)
Dim maxRent As Integer = CType(Request.QueryString( "MaxRent") , Integer)
Dim bathrooms As Integer = CType(Request.QueryString( "Bathrooms "), Integer)
Dim bedrooms As Integer = CType(Request.QueryString( "Bedrooms" ), Integer)
Dim fireplace As Boolean = CType(Request.QueryString( "Fireplace "), Boolean)
Dim clubhouse As Boolean = CType(Request.QueryString( "Clubhouse "), Boolean)
Dim smoking As Boolean = CType(Request.QueryString( "Smoking") , Boolean)
'declare Connection and datareader
Dim conn As New SqlClient.SqlConnection("M y Connection String Goes Here")
Dim rdr As SqlClient.SqlDataReader
'declare command object
Dim cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = conn
'add parameters
Dim p As SqlClient.SqlParameter
p = New SqlClient.SqlParameter("@m inRent", SqlDbType.Int)
p.Value = IIf(minRent = -1, DBNull.Value, minRent)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@m axRent", SqlDbType.Int)
p.Value = IIf(maxRent = -1, DBNull.Value, maxRent)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@b athrooms", SqlDbType.Int)
p.Value = IIf(bathrooms = -1, DBNull.Value, bathrooms)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@b edrooms", SqlDbType.Int)
p.Value = IIf(bedrooms = -1, DBNull.Value, bedrooms)
cmd.Parameters.Add(p)
'for fireplace and clubhouse, if user did not check box, assign
'null to the parameter because it likely means "no preference"
p = New SqlClient.SqlParameter("@f ireplace", SqlDbType.Bit)
p.Value = IIf(fireplace = False, DBNull.Value, True)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@c lubhouse", SqlDbType.Bit)
p.Value = IIf(clubhouse = False, DBNull.Value, True)
cmd.Parameters.Add(p)
'Unlike fireplace and clubhouse, if user does not check
'smoking then they probably are looking for non-smoking
'apartments.
p = New SqlClient.SqlParameter("@s moking", SqlDbType.Bit)
p.Value = smoking
cmd.Parameters.Add(p)
cmd.CommandText = "select * from Apartments where " & _
"(@minRent is null or rent >= @minRent) and " & _
"(@maxRent is null or rent <= @maxRent) and " & _
"(@bathrooms is null or bathrooms >= @bathrooms) and " & _
"(@bedrooms is null or bedrooms >= @bedrooms) and " & _
"(@fireplace is null or fireplace = @fireplace) and " & _
"(@clubhouse is null or clubhouse = @clubhouse) and " & _
"(smoking = @smoking)"
'run query and bind to a datagrid
conn.Open()
rdr = cmd.ExecuteReader()
DataGrid1.DataSource = rdr
DataGrid1.DataBind()
rdr.Close()
conn.Close()
End Sub
Well I hope that helps a little bit more. Let me know if you have more questions or run into problems
-Ian
Ok so let's say you have webform1 which is where the user selects all the stuff and then you response.redirect to webform2 and pass a querystring. Webform2 is where you build and run the query.
Now on webform1, you'll have some textboxes for min and max rent. If the user leaves them blank we know they have no preference about rent. This assumes the database table for your apartments stores and integer value for how much the rent is for each unit, for instance 500, 999, 650, etc:
<asp:TextBox id="tbxMinRent" runat="server"></asp:TextB
<asp:TextBox id="tbxMaxRent" runat="server"></asp:TextB
You also have radio button lists, say for things like # of bathrooms, bedrooms, etc. By default we will have the "No Preference" option selected and a value of -1 which is a flag indicating the user does not care how many the apartment has:
<asp:RadioButtonList id="rblBathrooms" runat="server">
<asp:ListItem Selected="True" Value="-1">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList id="rblBedrooms" runat="server">
<asp:ListItem Value="-1" Selected="True">No Preference</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
Finally, you have a checkbox list indicating yes or no for some other amenities. Generally, if user checks the box that would mean they do want that amenity (for instance, a fireplace). However if user does not check the box it probably means they don't care, (for instance user does not specifically want a fireplace or clubhouse, but probably wouldn't be opposed if the unit actually came with it). Perhaps a distinction could be made for Smoking, however, where if the user selects smoking they want a smoking unit and if they do not check smoking then they probably do NOT want a unit that allows smoking (or has been smoked in):
<asp:CheckBoxList id="cblAmenities" runat="server">
<asp:ListItem Value="Fireplace">Fireplac
<asp:ListItem Value="Smoking">Smoking</a
<asp:ListItem Value="Clubhouse">Clubhous
</asp:CheckBoxList>
Finally, on webform1 there is a button that the user clicks to run the search. This button will validate the page and redirect to webform2 after forming the querystring:
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button
In the code behind for webform1, you will have a function for the button click. First we will see if user typed anything in the rent textboxes. If user typed nothing we will assign the -1 (no preference) flag. Otherwise we assign whatever value user typed in. Next we assign the values for bathrooms and bedrooms. Again if "no preference" was selected, the -1 flag gets assigned. Finally, we'll declare some booleans for the checkboxlist (which i called cblAmenities). Then we loop through the listitems and check each one for whether it is true or false, then assign as appropriate. Lastly, we response.redirect to webform2 and formulate the querystring that will get passed along:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim minRent As Integer = IIf(tbxMinRent.Text.Length
Dim maxRent As Integer = IIf(tbxMaxRent.Text.Length
Dim bathrooms As Integer = rblBathrooms.SelectedValue
Dim bedrooms As Integer = rblBedrooms.SelectedValue
'Check box list stuff
Dim Fireplace As Boolean
Dim Clubhouse As Boolean
Dim Smoking As Boolean
Dim i As Integer 'Counter for looping
For i = 0 To cblAmenities.Items.Count - 1
If cblAmenities.Items(i).Text
Fireplace = cblAmenities.Items(i).Sele
End If
If cblAmenities.Items(i).Text
Clubhouse = cblAmenities.Items(i).Sele
End If
If cblAmenities.Items(i).Text
Smoking = cblAmenities.Items(i).Sele
End If
Next
Response.Redirect("webform
"MinRent=" & minRent.ToString() & _
"&MaxRent=" & maxRent.ToString() & _
"&Bathrooms=" & bathrooms.ToString() & _
"&Bedrooms=" & bedrooms.ToString() & _
"&Fireplace=" & Fireplace.ToString() & _
"&Clubhouse=" & Clubhouse.ToString() & _
"&Smoking=" & Smoking.ToString())
End Sub
On to webform2 where we run the query. I added a basic datagrid called DataGrid1 to this page.
<asp:datagrid id="DataGrid1" runat="server"></asp:datag
In the code-behind for webform2, I have the Page_Load function. First is to get the values off the querystring. Next I declare the sql objects I need. Instead of a stored procedure, I am just formulating the select statement in this function. Note for most of the parameters, if the user has "no preference" i assign it a value of NULL (by using dbnull.value). In the actual select statement's "where" clause, I go through each filter item and check - Is the variable null? That means the user had no preference so I move on to the next item. If the variable is not null, the user must have a preference so I check that the record meets the criteria. Finally I open my connection, execute the datareader, and then bind the results to my basic datagrid.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get values from querystring
Dim minRent As Integer = CType(Request.QueryString(
Dim maxRent As Integer = CType(Request.QueryString(
Dim bathrooms As Integer = CType(Request.QueryString(
Dim bedrooms As Integer = CType(Request.QueryString(
Dim fireplace As Boolean = CType(Request.QueryString(
Dim clubhouse As Boolean = CType(Request.QueryString(
Dim smoking As Boolean = CType(Request.QueryString(
'declare Connection and datareader
Dim conn As New SqlClient.SqlConnection("M
Dim rdr As SqlClient.SqlDataReader
'declare command object
Dim cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = conn
'add parameters
Dim p As SqlClient.SqlParameter
p = New SqlClient.SqlParameter("@m
p.Value = IIf(minRent = -1, DBNull.Value, minRent)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@m
p.Value = IIf(maxRent = -1, DBNull.Value, maxRent)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@b
p.Value = IIf(bathrooms = -1, DBNull.Value, bathrooms)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@b
p.Value = IIf(bedrooms = -1, DBNull.Value, bedrooms)
cmd.Parameters.Add(p)
'for fireplace and clubhouse, if user did not check box, assign
'null to the parameter because it likely means "no preference"
p = New SqlClient.SqlParameter("@f
p.Value = IIf(fireplace = False, DBNull.Value, True)
cmd.Parameters.Add(p)
p = New SqlClient.SqlParameter("@c
p.Value = IIf(clubhouse = False, DBNull.Value, True)
cmd.Parameters.Add(p)
'Unlike fireplace and clubhouse, if user does not check
'smoking then they probably are looking for non-smoking
'apartments.
p = New SqlClient.SqlParameter("@s
p.Value = smoking
cmd.Parameters.Add(p)
cmd.CommandText = "select * from Apartments where " & _
"(@minRent is null or rent >= @minRent) and " & _
"(@maxRent is null or rent <= @maxRent) and " & _
"(@bathrooms is null or bathrooms >= @bathrooms) and " & _
"(@bedrooms is null or bedrooms >= @bedrooms) and " & _
"(@fireplace is null or fireplace = @fireplace) and " & _
"(@clubhouse is null or clubhouse = @clubhouse) and " & _
"(smoking = @smoking)"
'run query and bind to a datagrid
conn.Open()
rdr = cmd.ExecuteReader()
DataGrid1.DataSource = rdr
DataGrid1.DataBind()
rdr.Close()
conn.Close()
End Sub
Well I hope that helps a little bit more. Let me know if you have more questions or run into problems
-Ian
ASKER
Thanks for all of your help. I really apreciate it. I was able to get what I wanted based on the advice you gave me. Now, one more final question to make this really easy: How do I close this out so you get credit?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
At the top you have:
Dim apartmentid As Integer
And near the bottom you try to assign a parameter but apartmentID has never been initialized with a value:
mycommand.Parameters("@apa
Any chance you could write a stored procedure for this?
If so, what I would do is just assign all the variables. In the cases where user picks "no preference" then just leave it null. Your stored proc will take all those values but have defaults of null.
Something like
create procedure GetApartmentList
@ApartmentID int = null
, @bathrooms int = null
, etc
then the select is like
select * from MyTable
where
(@ApartmentID is null or ApartmentID = @ApartmentID) and
(@bathrooms is null or bathrooms = @bathrooms)
etc
Basically it only filters on a variable when you passed in a value. If you left it null, it basically will skip over filtering on that.