Solved

Use a checkbox to change the query

Posted on 2012-04-10
13
307 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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

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
 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
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.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

821 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