Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Use a checkbox to change the query

Posted on 2012-04-10
13
Medium Priority
?
311 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

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.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

876 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