Solved

Use a checkbox to change the query

Posted on 2012-04-10
13
305 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

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…
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…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

912 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

22 Experts available now in Live!

Get 1:1 Help Now