Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 3.5 > ASP.NET 3.5 Basics
|
ASP.NET 3.5 Basics If you are new to ASP or ASP.NET programming with version 3.5, this is the forum to begin asking questions. Please also see the Visual Web Developer 2008 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 3.5 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old December 3rd, 2008, 11:34 AM
Authorized User
 
Join Date: Mar 2008
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default CheckboxList and SQLDataSource

Can you pass multiple selected values from a checkboxlist into the WHERE clause of a SQL statement?

If so, how do you go about accomplishing this?

 
Old December 3rd, 2008, 01:42 PM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

You say you want to do this with an SQLDataSource... if so, the easiest way I can think of is to dynamically manipulate the Select command at runtime.

Here is an example using the Northwind database:

In the Page, we have a checkbox list populated by the categories table, and a GridView populated by the products table.

Code:
<asp:CheckBoxList ID="cbxCategories" runat="server" DataSourceID="SqlDataSourceCategories"
   DataTextField="CategoryName" DataValueField="CategoryID" AutoPostBack="True">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSourceCategories" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName]">
</asp:SqlDataSource>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ProductID"
   DataSourceID="SqlDataSourceProducts" AutoGenerateColumns="True">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   SelectCommand="SELECT ProductID, ProductName FROM Products"></asp:SqlDataSource>
Above, we have set the checkboxlist to automatically post back. When a user checks any category, we want to populate the Gridview with products from that category. If the user checks on more than one category, we want the Gridview to contain products of all the checked categories.

The handler for the checkboxlist postback would look like this:

Code:
    Protected Sub cbxCategories_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) _ 
        Handles cbxCategories.SelectedIndexChanged
        Dim whereClause As String = " WHERE "
        For Each item As ListItem In cbxCategories.Items
            If item.Selected Then
                whereClause += "CategoryID = " & item.Value & " OR "
            End If
        Next
        SqlDataSourceProducts.SelectCommand += whereClause.Substring(0, whereClause.Length - 4)
    End Sub
This will generate a dynamic WHERE clause with an OR for each checked item.

_________________________________

Visit my blog at http://leedumond.com
 
Old December 3rd, 2008, 02:21 PM
Authorized User
 
Join Date: Mar 2008
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thanks! I configured your code so that it looks like this:

    Protected Sub cblCourse_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles cblCourse.SelectedIndexChanged
        Dim whereClause As String = " WHERE "
        For Each item As ListItem In cblCourse.Items
            If item.Selected Then
                whereClause += "CourseID = " & item.Value & " OR "
            End If
        Next
        SqlDataSource3.SelectCommand += whereClause.Substring(0, whereClause.Length - 4)
    End Sub


BUT....

I get this error when attempting to select an item from the checkboxlist:


Incorrect syntax near the keyword 'WHERE'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[SqlException (0x80131904): Incorrect syntax near the keyword 'WHERE'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolean breakConnection) +925466
   System.Data.SqlClient.SqlInternalConnection.OnErro r(SqlException exception, Boolean breakConnection) +800118
   System.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObject stateObj) +186
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932
   System.Data.SqlClient.SqlDataReader.ConsumeMetaDat a() +31
   System.Data.SqlClient.SqlDataReader.get_MetaData() +62
   System.Data.SqlClient.SqlCommand.FinishExecuteRead er(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
   System.Data.SqlClient.SqlCommand.RunExecuteReaderT ds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1005
   System.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
   System.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehavior behavior, String method) +122
   System.Data.SqlClient.SqlCommand.ExecuteDbDataRead er(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.System.Data.IDbComman d.ExecuteReader(CommandBehavior behavior) +7
   System.Data.Common.DbDataAdapter.FillInternal(Data Set dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +141
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +137
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +83
   System.Web.UI.WebControls.SqlDataSourceView.Execut eSelect(DataSourceSelectArguments arguments) +1770
   System.Web.UI.DataSourceView.Select(DataSourceSele ctArguments arguments, DataSourceViewSelectCallback callback) +17
   System.Web.UI.WebControls.DataBoundControl.Perform Select() +149
   System.Web.UI.WebControls.BaseDataBoundControl.Dat aBind() +70
   System.Web.UI.WebControls.GridView.DataBind() +4
   System.Web.UI.WebControls.BaseDataBoundControl.Ens ureDataBound() +82
   System.Web.UI.WebControls.GridView.OnPreRender(Eve ntArgs e) +24
   System.Web.UI.Control.PreRenderRecursiveInternal() +86
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041




 
Old December 3rd, 2008, 02:24 PM
Authorized User
 
Join Date: Mar 2008
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default

here is the markup for the CheckboxList:

<asp:CheckBoxList ID="cblCourse" runat="server"
            DataSourceID="SqlDataSource1" DataTextField="Course"
            DataValueField="Course" CellPadding="2" CellSpacing="2" Height="25px"
            RepeatColumns="4" RepeatDirection="Horizontal" Width="1138px"
            AutoPostBack="True">
        </asp:CheckBoxList>

 
Old December 3rd, 2008, 02:26 PM
Authorized User
 
Join Date: Mar 2008
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default

for viewing's sake, here is the markup for SQLDataSource3:


  <asp:SqlDataSource ID="SqlDataSource3" runat="server"
            ConnectionString="<%$ ConnectionStrings:CS_Scores %>" SelectCommand="SELECT AVG(SessionFlow) AS SessionFlow, AVG(Materials) AS Materials, AVG(CBT) AS CBT, AVG(Activities) AS Activities, AVG(ClarityOfInfo) AS ClarityOfInfo, AVG(ClassLength) AS ClassLength, AVG(AnswerQs) AS AnswerQs, AVG(Patience) AS Patience, AVG(Presentation) AS Presentation, AVG(Knowledge) AS Knowledge, AVG(Timeliness) AS Timeliness, AVG(Preparedness) AS Preparedness, AVG(Motivation) AS Motivation, AVG(Participation) AS Participation FROM View_3 WHERE (Course = @Course) AND (Instructor = @Instructor) AND (CourseDate &gt;= @CourseDate) AND (CourseDate &lt;= @CourseDate2)
">
            <SelectParameters>
                <asp:ControlParameter ControlID="cblCourse" Name="Course"
                    PropertyName="SelectedValue" Type="String" />
                <asp:ControlParameter ControlID="ddlInstructor" Name="Instructor"
                    PropertyName="SelectedValue" Type="String" />
                <asp:ControlParameter ControlID="bdpStartDate" Name="CourseDate"
                    PropertyName="SelectedDate" />
                <asp:ControlParameter ControlID="bdpEndDate" Name="CourseDate2"
                    PropertyName="SelectedDate" />
            </SelectParameters>
        </asp:SqlDataSource>




And here is the markup for the Gridview:

      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource3">
            <Columns>
                <asp:BoundField DataField="SessionFlow" DataFormatString="{0:F}"
                    HeaderText="SessionFlow" ReadOnly="True" SortExpression="SessionFlow" />
                <asp:BoundField DataField="Materials" DataFormatString="{0:F}"
                    HeaderText="Materials" ReadOnly="True" SortExpression="Materials" />
                <asp:BoundField DataField="CBT" DataFormatString="{0:F}" HeaderText="CBT"
                    ReadOnly="True" SortExpression="CBT" />
                <asp:BoundField DataField="Activities" DataFormatString="{0:F}"
                    HeaderText="Activities" ReadOnly="True" SortExpression="Activities" />
                <asp:BoundField DataField="ClarityOfInfo" DataFormatString="{0:F}"
                    HeaderText="ClarityOfInfo" ReadOnly="True" SortExpression="ClarityOfInfo" />
                <asp:BoundField DataField="ClassLength" DataFormatString="{0:F}"
                    HeaderText="ClassLength" ReadOnly="True" SortExpression="ClassLength" />
                <asp:BoundField DataField="AnswerQs" DataFormatString="{0:F}"
                    HeaderText="AnswerQs" ReadOnly="True" SortExpression="AnswerQs" />
                <asp:BoundField DataField="Patience" DataFormatString="{0:F}"
                    HeaderText="Patience" ReadOnly="True" SortExpression="Patience" />
                <asp:BoundField DataField="Presentation" DataFormatString="{0:F}"
                    HeaderText="Presentation" ReadOnly="True" SortExpression="Presentation" />
                <asp:BoundField DataField="Knowledge" DataFormatString="{0:F}"
                    HeaderText="Knowledge" ReadOnly="True" SortExpression="Knowledge" />
                <asp:BoundField DataField="Timeliness" DataFormatString="{0:F}"
                    HeaderText="Timeliness" ReadOnly="True" SortExpression="Timeliness" />
                <asp:BoundField DataField="Preparedness" DataFormatString="{0:F}"
                    HeaderText="Preparedness" ReadOnly="True" SortExpression="Preparedness" />
                <asp:BoundField DataField="Motivation" DataFormatString="{0:F}"
                    HeaderText="Motivation" ReadOnly="True" SortExpression="Motivation" />
                <asp:BoundField DataField="Participation" DataFormatString="{0:F}"
                    HeaderText="Participation" ReadOnly="True" SortExpression="Participation" />
            </Columns>
        </asp:GridView>

 
Old December 3rd, 2008, 03:19 PM
Lee Dumond's Avatar
Wrox Author
 
Join Date: Jan 2008
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

You have an existing WHERE clause on your SelectCommand. By using the code I gave you, you are tacking on another where clause, so now you have TWO "Wheres", which is not allowed.

You will have to change the way the string is being constructed in the loop such that it constructs a string using proper syntax, with the string you define in the markup as the "starting" point.

_________________________________

Visit my blog at http://leedumond.com





Similar Threads
Thread Thread Starter Forum Replies Last Post
Checkboxlist epkgupta Visual Studio 2005 0 March 11th, 2008 05:31 AM
checkboxlist problems hanoisky ASP.NET 2.0 Basics 1 December 6th, 2006 06:04 PM
CheckBoxList and SqlDataSource extendedram ASP.NET 2.0 Basics 2 June 8th, 2006 02:54 PM
CheckBoxList stu9820 ASP.NET 1.0 and 1.1 Basics 10 May 25th, 2006 08:15 PM
CheckBoxList eddiema VS.NET 2002/2003 1 April 9th, 2004 09:49 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.