Use a checkbox to change the query

I have added a checkbox to my asp.net code :
<form id="form1" runat="server">
 <asp:CheckBox ID="Children"  Text="Children" runat="server" />

When checked it should add a where to my selectcommand :

 <%
          if (Children.Checked==true)
          { %> <asp:SqlDataSource ID="SqlDataSourceEmpList" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Cursisten] WHERE CHILDREN='True' ORDER BY [Name]">
     </asp:SqlDataSource>
     <% }
          else
          {%>  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Cursisten] ORDER BY [Name]">
     </asp:SqlDataSource>  <% }      
             
           %>
 

Problem is, the site begins without the checked and yet the sqlcommqnd is executed WITH the where-clause.

Also, how can I make it work that when the checkbox is checked or unchecked in realtime that the sqlcommqnd is altered ??
troostersAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anuradha GoliSystems Development / Support SpecialistCommented:
initially set the check box value checked to false and then try ..hope it will help
hafeezmcaCommented:
Hi,

Do you want to execute the command on checkbox click event or on some button event.
In case if you want it to be on checkbox click event try this:

Configure sqldatasource at design time or in page_load event and load your data without the where clause.

Go the the codebehind and add an event handler for the click event (just double click the checkbox control)

Now in this event just add the selectcommand of the datasource with the select command and execute it.
In case if you are binding with some grid then you have to bind it again.

In case if you are planning to handle it on a button click then check the status of the checkbox if its selected or not by If condition and follow the above steps in the command button event.
troostersAuthor Commented:
Yes, I want it to be executed when the checkbox changes.

But how can I add my sqlcommand in code-behind so the <asp:ListView   is refreshed ?
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

troostersAuthor Commented:
Ok, so I have now in my .aspx file this :
    <asp:CheckBox ID="Children"  Text="Children" runat="server" Checked="false"
        AutoPostBack="true" oncheckedchanged="Children_CheckedChanged1"/>

<asp:ListView ID="lvwEmployees" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSourceEmpList" >

and in the codebehind :

 protected void Children_CheckedChanged(object sender, EventArgs e)
        {

            SqlConnection ConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["kopaConnectionString"].ConnectionString);
            string queryString = "";

            if (Children.Checked == true)
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='True' ORDER BY [Name]";
            }
            else
            {
                queryString = "SELECT * FROM [Cursisten] ORDER BY [Name]";
            }
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, ConnectionString);

            System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataAdapter.Fill(dataSet);
            lvwEmployees.DataBind();


But when I check the checkbox, the databind does not seem to do anything. The list is not refilled.
hafeezmcaCommented:
Hi, Could you check if Autopost of the checkbox is set to True.
troostersAuthor Commented:
Yes, it is.
hafeezmcaCommented:
Hi,
You need to add the FilterExpression as mentioned below:

SelectCommand="Select * from Customers"
  ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>"
  FilterExpression="country = '{0}'">

Read more over here:

http://forums.asp.net/t/1367899.aspx/1

http://msdn.microsoft.com/en-us/library/59bfya48(VS.85).aspx
troostersAuthor Commented:
If I add that my webpage doesn't even start.
dhawalsethCommented:
Hi Trooster,
Have a look below:

 System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataAdapter.Fill(dataSet);
//you need to set the datasource of the list view here before calling the databind.
            lvwEmployees.DataBind();

Open in new window


Please check you haven't set a datasource prior to databind.

Mark as answer if helped.

Enjoy!!.
troostersAuthor Commented:
I tried it yesterday with a datasource like :

System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, ConnectionString);

            SqlDataAdapter ada = new SqlDataAdapter(queryString, ConnectionString);
            DataTable dtEmp = new DataTable();
                ada.Fill(dtEmp);

               if (!IsPostBack)
                {
                    lvwEmployees.DataSource = dtEmp;
                    lvwEmployees.DataBind();
                }

But that did not help.
troostersAuthor Commented:
My full codebehind is now :
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        protected void Children_CheckedChanged1(object sender, EventArgs e)
        {
            SqlConnection ConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["kopaConnectionString"].ConnectionString);
            string queryString = "";

            if (Children.Checked)
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='true' ORDER BY [Name]";
            }
            else
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='true' ORDER BY [Name]";
            }
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, ConnectionString);

           /* SqlDataAdapter ada = new SqlDataAdapter(queryString, ConnectionString);
            DataTable dtEmp = new DataTable();
                ada.Fill(dtEmp);
            */
           System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataAdapter.Fill(dataSet);
                if (!IsPostBack)
                {
                    lvwEmployees.DataSource = dataSet;
                    lvwEmployees.DataBind();
                }


            MessageBox("ok");



        }

Open in new window

dhawalsethCommented:
Hey the code you posted above will only set the datasource once, if the page is reloaded datasource and databind will not happen.

in the check changed code you posted above, try the following code:
protected void Children_CheckedChanged(object sender, EventArgs e)
        {

            SqlConnection ConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["kopaConnectionString"].ConnectionString);
            string queryString = "";

            if (Children.Checked == true)
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='True' ORDER BY [Name]";
            }
            else
            {
                queryString = "SELECT * FROM [Cursisten] ORDER BY [Name]";
            }
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, ConnectionString);

            System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataAdapter.Fill(dataSet);
lvwEmployees.DataSource = dataSet;
            lvwEmployees.DataBind();

Open in new window


Please note:
when you want to bind your listview conditionally, you have to follow the steps below:
1. Bind your list view in the (!IsPostBack) on page load event.
2. On event where you want to rebind your control you call the databind code again, so that when you post back your control is bind to your conditional datasource.

The code you posted above will look like this:
protected void Children_CheckedChanged1(object sender, EventArgs e)
        {
            SqlConnection ConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["kopaConnectionString"].ConnectionString);
            string queryString = "";

            if (Children.Checked)
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='true' ORDER BY [Name]";
            }
            else
            {
                queryString = "SELECT * FROM [Cursisten] WHERE CHILDREN='true' ORDER BY [Name]";
            }
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, ConnectionString);

           /* SqlDataAdapter ada = new SqlDataAdapter(queryString, ConnectionString);
            DataTable dtEmp = new DataTable();
                ada.Fill(dtEmp);
            */
           System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataAdapter.Fill(dataSet);
               if(dataSet != null)
{
                    lvwEmployees.DataSource = dataSet;
                    lvwEmployees.DataBind();               
}

            MessageBox("ok");



        }
                                      

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
troostersAuthor Commented:
Ok, I solved it by adding the sqlconnection and binding to my page_load and removing the DatasourceID from my listview :

    <asp:ListView ID="lvwEmployees" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSourceEmpList" >


But now I have a new problem , when I click on the SELECT button in my listview, I do not get to see my detailsview anymore ??
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.