Category Archives: CheckBoxList

[RESOLVED] Check Box Select All Validation

<input id="ContentPlaceHolder1_chkAll" name="ctl00$ContentPlaceHolder1$chkAll" type="checkbox" />


<input id="ContentPlaceHolder1_CheckBoxList1_0" value="1" name="ctl00$ContentPlaceHolder1$CheckBoxList1$0" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_1" value="2" name="ctl00$ContentPlaceHolder1$CheckBoxList1$1" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_2" value="3" name="ctl00$ContentPlaceHolder1$CheckBoxList1$2" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_3" value="4" name="ctl00$ContentPlaceHolder1$CheckBoxList1$3" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_4" value="5" name="ctl00$ContentPlaceHolder1$CheckBoxList1$4" type="checkbox" />

 

<asp:CheckBox ID="chkAll" runat="server" onclick="return CheckUnCheckAll();" Text="Select All" />
                                    <hr />
                                    <asp:CheckBoxList ID="CheckBoxList1" onclick="return CheckUnCheckList();" runat="server">
                                        <asp:ListItem Value="1" Text="Forecast & Sales Price Data"></asp:ListItem>
                                        <asp:ListItem Value="2" Text="Production & BPP Price Data"></asp:ListItem>
                                        <asp:ListItem Value="3" Text="Inventory & Tankage Data"></asp:ListItem>
                                        <asp:ListItem Value="4" Text="Transit Time Data"></asp:ListItem>
                                        <asp:ListItem Value="5" Text="Transportation Modes Data"></asp:ListItem>
                                    </asp:CheckBoxList>
                                    <asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="sandValidation"
                                        ForeColor="Red" Display="Dynamic" runat="server" ErrorMessage="Please Check atleast 1 Data for upload."
                                        ToolTip="Please Check atleast 1 Data for upload." ValidationGroup="vgSand">*</asp:CustomValidator>

 

 

<script type="text/javascript" language="javascript">
        function sandValidation(sender, args) {
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');
            var ischecked = false;
            args.IsValid = false;
            for (i = 0; i < options.length; i++) {
                var opt = options[i];
                if (opt.type == "checkbox") {
                    if (opt.checked) {
                        ischecked = true;
                        args.IsValid = true;
                    }
                }
            }
        }
        function CheckUnCheckAll() {
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');

            var temp = '<%=chkAll.ClientID%>'
            var _chkControl = document.getElementById(temp);

            if (_chkControl.checked == true) {
                for (i = 0; i < options.length; i++) {
                    var opt = options[i];
                    if (opt.type == "checkbox") {
                        opt.checked = true;
                    }
                }
            }
            else {
                for (i = 0; i < options.length; i++) {
                    var opt = options[i];
                    if (opt.type == "checkbox") {
                        opt.checked = false;
                    }
                }
            }
            return true;
        }
        function CheckUnCheckList() {
           
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');
            var ischecked = false;
            var isUnCheck = false;
            //            args.IsValid = false;
            for (i = 0; i < options.length; i++) {
                var opt = options[i];
                if (opt.type == "checkbox") {
                    if (opt.checked) {
                        ischecked = true;
                        //                        args.IsValid = true;
                    }
                    else {
                        isUnCheck = true;
                    }
                }
            }
           
            if (isUnCheck == true) {
                var temp = '<%=chkAll.ClientID%>'
                var _chkControl = document.getElementById(temp);
                _chkControl.checked = false;

            }
        }
    </script>

Whats the problem you are facing. Your code is working fine.

[RESOLVED] Scrollable checkboxlist

Hi I am using ASP.NET 2.0

Does anyone know if it is possible to create a vertically scrollable Checkboxlist WITHOUT using a DIV

I have to build my controls using server code, hence cannot use a div. Any ideas?

Thanks

Hi use div and acces it in server side like this

 

<div id="diva" runat="server">

Checkbox goes here

</div>

 

http://www.justin-cook.com/wp/2006/04/30/create-a-scrolling-check-box-list/

 

 

Hi sunsilk10,

the CheckboxList control outputs tables. Tables dont support the overflow CSS property. What you can do is wrap the control within div tags

and set the style of the div tags overflow property to auto like this :<div style="overflow: auto;height:100px;width:200px;">

   <asp:CheckBoxList id="CheckBoxList1" runat="server"></asp:CheckBoxList>
  </div>

Now if the width of your checkboxList exceeds the height of your div, that is 100px you get vertical scrollbars and if the width exceeds 200px you have

horizontal scrollbars.

Please check the following link:

http://www.dotnetmonster.com/Uwe/Forum.aspx/asp-net-web-controls/1565/How-to-add-a-vertical-scroll-bar-to-a-CheckBoxList

http://www.velocityreviews.com/forums/t101116-vertical-scroll-bar-with-checkboxlist-in-asp-net.html

If you are using the CheckBoxList control in ASP.Net, or you just have a bunch of options for users to check, a large number of check boxes options can take up a lot of room on your web page. Also, you may have a <select> with a lot of options, you need to allow multiple selects, but it also takes up a lot of room, and having the user hold CTRL to select multiple items is a nuisance. Well, this little DHTML idea will allow you to combine many checkboxes into a pseudo drop-down list. It makes for one slick and user-friendly solution!

 

So basically, you just need to place the CheckBoxList, or any list for that matter in a <div>. The div will have an initial height of a few pixels, just enough to see the 'title'. When you move the mouse over the title, the CheckBoxList will "drop down" like a menu. We will accomplish that by changing the height. Also, we will give it a <select> menu feel by adding a scrollbar.

 

You can see an example of this at this dental search engine. It's under advanced search.

 

Here's the ASP.Net code to generate the list. You can use any other language of course, and put whatever other list in the <div you'd like:

 

 

<div id="list_countries">Please choose the countries to search:<br />

  <asp:CheckBoxList ID="ListCountries" DataSourceID="DSCountries" DataValueField="id"  DataTextField="specialty" runat="server" />

  <asp:SqlDataSource ID="DSCountries" runat="server" ConnectionString="<%$ ConnectionStrings:Conn1 %>" SelectCommand="SELECT [id], [name] FROM [countries] ORDER BY [name]" />

</div>

 

Now if the width of your checkboxList exceeds the height of your div, that

is 100px you get vertical scrollbars and if the width exceeds 200px you have

horizontal scrollbars.

sunsilk10

I have to build my controls using server code, hence cannot use a div. Any ideas?

What do you mean by server code ?do you mean code behind file ? Are you building your checkbox list programatically ?

There also you can create <div> tags with runat="server"  and add your newly created checkboxs control to the <div> and ofcource you can apply the styles.

Did i understood your query ?

You can programatically create Panel control and add your other controls to that panel control.

I appogise for my previous post that i said 'you can create <div> programatically with runat="server" '.By Mistake i said that.

[RESOLVED] Looping thru CheckboxList to get selected values & save to database

I am fairly new to ASP.NET C#, I have a vehicle table which stores basic info about the vehicle, then a vehicle options table that stores the options available on the table.

 

I have a checkboxlist control on my form and I am populating the list items from the database.  I am trying to loop thru the items to determine which ones the user has selected.  After determining which ones are selected I need to add rows for each item selected to the vehicle options table.

 

I could use some help getting my code to work:

 

sql = "INSERT INTO Vehicle_Options (VehicleID, OptionID) VALUES (@VehicleID, @OptionID)";

        //add parameters for query
        cmd.Parameters.Add(new SqlParameter("@OptionID", SqlDbType.Int));
        cmd.Parameters.Add(new SqlParameter("@VehicleID", SqlDbType.Int));
              

        foreach (ListItem cBox in chkAirCondition.Items)
        {
            if (cBox.Selected)
            {
                cmd.Parameters["@VehicleID"].Value = Id;
                cmd.Parameters["@OptionID"].Value = cBox.Value;
            }
        }

        cmd.ExecuteNonQuery();

Every time I loop thru and find another value, I think I am overwriting the previous value.  
How can I do this when I have a dynamic list of values and don't know how many records I will be
adding to the database.

If you want to retain your existing code structure, try moving cmd.ExecuteNonQuery() into the for loop, after you have set the parameter values:

 

sql = "INSERT INTO Vehicle_Options (VehicleID, OptionID) VALUES (@VehicleID, @OptionID)";
 
        //add parameters for query
        cmd.Parameters.Add(new SqlParameter("@OptionID", SqlDbType.Int));
        cmd.Parameters.Add(new SqlParameter("@VehicleID", SqlDbType.Int));
               
 
        foreach (ListItem cBox in chkAirCondition.Items)
        {
            if (cBox.Selected)
            {
                cmd.Parameters["@VehicleID"].Value = Id;
                cmd.Parameters["@OptionID"].Value = cBox.Value;
                cmd.ExecuteNonQuery();
            }
        }

 

Though I would recommend re-writing to build and execute the entire insert for each iteration.

i think u need to do follow

foreach (ListItem cBox in chkAirCondition.Items)
        {
            if (cBox.Selected)
            {
                sql = "INSERT INTO Vehicle_Options (VehicleID, OptionID) VALUES (@VehicleID, @OptionID)";
                //add parameters for query
                cmd.Parameters.Add(new SqlParameter("@OptionID", SqlDbType.Int));
                cmd.Parameters.Add(new SqlParameter("@VehicleID", SqlDbType.Int));

                cmd.Parameters["@VehicleID"].Value = Id;
                cmd.Parameters["@OptionID"].Value = cBox.Value;
                cmd.ExecuteNonQuery();
            }
        }

on Save button click event

You might want to change your code to below and add below namespace  :

using System.Configuration;
CommaDelimitedStringCollection strVal = new CommaDelimitedStringCollection();
 cmd.Parameters["@VehicleID"].Value = Id;
 
foreach (ListItem cBox in chkAirCondition.Items)
{
            if (cBox.Selected)
            {
                
                strVal.Add(cBox.Value);
            }
}
 cmd.Parameters["@OptionID"].Value = strVal.ToString();
 cmd.ExecuteNonQuery();

As you're passing commadelimited string, you need to get table out of it for which you can use Split function in your sql server stored procedure.

 

[RESOLVED] how to retrieve data saved in sql db into checkboxlist

Hi...

I've used checkboxlist to insert data into the sql database...

example... checkboxlist have values 1,2,3,4,5... If is select 1,3 and 5 the values stored in databse will be 1,3,5.

Now i want to retrieve those values into similar checkboxlist(1,2,3,4,5), but only 1,3 and 5 saved in db should be selected, 2 and 4 unselected....

help me...

thanks in advance...

 

Please share your db structure. You may get all the data from table and then run a loop and assign checked =true for those checkboxes that are stored in db.

If you are binding with checkboxes from db with the help of a boolean field then you can do so. (asuming that the five element you want to store are stored in separate db table. Suppose table1 have all five element stored and in table2 only selected are stored based on some criterio.)

 

select description,true from table2 where......

union

select description,false from table1 where id not in (select id from table1 where.....)

If you simply are trying to reload the select you could more easily do a join on your dataset and create a IsSelected column.  Then when you bind it to the CheckboxList you set the Selected property accordingly.  For example, if the following is what you use to populate the CheckboxList normally:

SELECT VALUE
FROM CHECKBOX_VALUES

and this is where you store the results:

SELECT VALUE
FROM CHECKBOX_SELECTED

Then you want to always use the following:

SELECT CB.VALUE, CASE WHEN CBS.VALUE IS NOT NULL THEN 1 ELSE 0 END AS IS_SELECTED
FROM CHECKBOX_VALUES CB
LEFT OUTER JOIN CHECKBOX_SELECTED CBS ON CB.VALUE = CBS.VALUE 

Once the data is bound simply do a for each loop through the data rows and set the selected value for item:

Dim myData As DataTable = GetCheckBoxData()
myList.DataSource = myData
myList.DataBind()

For Each Row As DataRow In myData.Rows
     If Row("IS_SELECTED") = 1 Then
          myList.Items.FindByValue(Row("VALUE")).Selected = True
     End If
Next

[RESOLVED] ASP.NET - Using checkbox from the calender control

I am implementing a leave system using the calender control. Something like below :-

 

enter image description here

Following is the markup :-

Following is the markup :-

<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender" 
      ShowGridLines="True">
    </asp:Calendar>
    <asp:DropDownList ID="DropDownList1" runat="server">
      <asp:ListItem Value="vacation" Text="Vacation" />
      <asp:ListItem Value="sick" Text="Sick" />
      <asp:ListItem Value="training" Text="Training" />
    </asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
Following is the code-behind :-

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
  {
    if (!e.Day.IsOtherMonth && !e.Day.IsWeekend)
    {
      CheckBoxList list = new CheckBoxList();
      list.Items.Add(new ListItem("Half day"));
      list.Items.Add(new ListItem("Full day"));
      e.Cell.Controls.Add(list);
    }

  }
However, I am not able to access the the checkbox values neither in the button_click event nor in the DayRender event? Could anybody help? Is there a better way to implement this?

You have to track the selection on clientside using a hidden field.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function setDate(date, option) {
            var hiddenField = document.getElementById('<%= hdnDates.ClientID %>');
            if (hiddenField.value == "")
                hiddenField.value = date + "-" + option;
            else
                hiddenField.value = hiddenField.value + "," + date + "-" + option;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="hidden" id="hdnDates" runat="server" />
    <asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar1_DayRender" ShowGridLines="True">
    </asp:Calendar>
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="vacation" Text="Vacation" />
        <asp:ListItem Value="sick" Text="Sick" />
        <asp:ListItem Value="training" Text="Training" />
    </asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
    </form>
</body>
</html>

Add two radiobuttons for Half Day and Full Day and set the hidden field with date and the option selected using Javascript and onclick event.

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    if (!e.Day.IsOtherMonth && !e.Day.IsWeekend)
    {
        e.Cell.Controls.Add(new Literal() { Text = "<br/>" });
        RadioButton rbHalfDay = new RadioButton() { Text = "Half Day", GroupName = e.Day.Date.ToShortDateString() };
        rbHalfDay.Attributes.Add("onclick""setDate('" + e.Day.Date.ToShortDateString() + "',0);");
        e.Cell.Controls.Add(rbHalfDay);
        e.Cell.Controls.Add(new Literal() { Text = "<br/>" });
        RadioButton rbFullDay = new RadioButton() { Text = "Full Day", GroupName = e.Day.Date.ToShortDateString() };
        rbFullDay.Attributes.Add("onclick""setDate('" + e.Day.Date.ToShortDateString() + "',1);");
        e.Cell.Controls.Add(rbFullDay);
    }
}
      
protected void Button1_Click(object sender, EventArgs e)
{
    var Dates = hdnDates.Value.Split(',').Select(a => new
    {
        Date = a.Split('-')[0],
        Option = a.Split('-')[1]
    }).ToList();
    foreach (var item in Dates)
    {
        string DateSelected = item.Date;
        //Option 0 for half day 1 for full day
        string option = item.Option;
    }
    hdnDates.Value = "";
}

You can parse the dates selected and the option selected in Button Click event. That's it. Try that example and see if it works for you.