Solved

Use a checkbox to change the query

Posted on 2012-04-10
13
303 Views
Last Modified: 2012-04-24
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 ??
0
Comment
Question by:troosters
  • 7
  • 3
  • 2
  • +1
13 Comments
 
LVL 12

Expert Comment

by:Anuradha Goli
ID: 37826681
initially set the check box value checked to false and then try ..hope it will help
0
 
LVL 5

Expert Comment

by:hafeezmca
ID: 37826945
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.
0
 

Author Comment

by:troosters
ID: 37827008
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 ?
0
 

Author Comment

by:troosters
ID: 37827150
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.
0
 
LVL 5

Expert Comment

by:hafeezmca
ID: 37828006
Hi, Could you check if Autopost of the checkbox is set to True.
0
 

Author Comment

by:troosters
ID: 37828016
Yes, it is.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 5

Expert Comment

by:hafeezmca
ID: 37828117
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
0
 

Author Comment

by:troosters
ID: 37828386
If I add that my webpage doesn't even start.
0
 
LVL 7

Expert Comment

by:dhawalseth
ID: 37831528
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!!.
0
 

Author Comment

by:troosters
ID: 37831591
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.
0
 

Author Comment

by:troosters
ID: 37831602
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

0
 
LVL 7

Accepted Solution

by:
dhawalseth earned 500 total points
ID: 37831608
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

0
 

Author Comment

by:troosters
ID: 37832155
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 ??
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem with SqlConnection 5 124
C# Reverse int in fast ways 6 29
JavaScript error 1 34
COnsume rest client 6 16
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now