I have a CheckBoxList like following
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBoxList1.Items.Add(new ListItem("Check/Uncheck All","0"));
CheckBoxList1.Items.Add(new ListItem("A","1"));
CheckBoxList1.Items.Add(new ListItem("B","2"));
CheckBoxList1.Items.Add(new ListItem("C", "3"));
CheckBoxList1.Items.Add(new ListItem("D", "4"));
}
}
I want whenever the first item is checked to check the rest of the items and whenever unchecked to uncheck the rest. Also the user can select every item separately.
I want do this with code behind without JavaScript or JQuery.
Try this
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
string result = Request.Form["__EVENTTARGET"];
int index1 = int.Parse(result.Substring(result.IndexOf("$") + 1));
if (index1 == 0)
{
bool tf = CheckBoxList1.Items[index1].Selected ? true : false;
CheckUncheckAll(tf);
}
}
void CheckUncheckAll(bool tf)
{
foreach (ListItem item in CheckBoxList1.Items)
{
item.Selected = tf;
}
}
for(int index = 0; index < checkedListBox.Items.Count; ++index)
{
checkedListBox.SetItemChecked(index, false);
}
With this piece of code, you could be able to access the checkbox from C# code behind and could be able to check/uncheck them or even enable/disable them. Hope it might help.
foreach (ListItem item in CheckBoxList.Items) {
item.Selected = true;
item.Enabled = true;
}
in .aspx page please add autopostback="true" for checkboxlist
then please add this event. Its working i have checked it.
Private Sub CheckBoxList1_SelectedIndexChsanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
Dim result As String = Request.Form("__EVENTTARGET")
Dim checkedBox As String() = result.Split("$"c)
Dim index As Integer = Integer.Parse(checkedBox(checkedBox.Length - 1))
If CheckBoxList1.Items(index).Text = "Check/Uncheck All" Then
Dim Chkbool As Boolean = CheckBoxList1.Items(index).Selected
For Each item In CheckBoxList1.Items
item.selected = Chkbool
Next
End If
End Sub
There is a generic way of having a select all item in asp CheckBoxList with using jquery.
You can have as many as CheckBoxList controls on the form with the select all functionality.
you only need to make sure
Your CheckBoxList has allowSelectAll Class
You added a ListItem to your checkbox list to allow users to select
All with the value of All
chkBoxList.Items.Insert(0, new ListItem("All", "All"));
you Only need the following code
<script>
$('.allowSelectAll :checkbox[value=All]').click(function () {
var toggle = this.checked;
$(this).closest('.allowSelectAll').find(":checkbox").attr("checked", toggle);
});
</script>
In the following code spinet I have 4 Checkbox lists
<div >
<label>Experience 1</label>
<asp:CheckBoxList ID="chklstExp1" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 2</label>
<asp:CheckBoxList ID="chklstExp2" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 3</label>
<asp:CheckBoxList ID="chklstExp3" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Location</label>
<asp:CheckBoxList ID="chklstLocation" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<asp:Button runat="server" ID="btnShowReport" OnClick="btnShowReport_Click" Text="Show Report"/>
</div>
For making items false you need to do:
checkList.ClearSelection();
For making items as true:
foreach (var item in checkList.Items.Cast<ListItem>().Where (li => li.Value == "1" || li.Value == "3" || li.Value == "5"))
{
item.Selected = true;
}
for Check all
foreach (ListItem item in CheckBoxList.Items)
{
item.Selected = true;
}
for unchek all
CheckBoxList.ClearSelection();
Related
I have multiple dropdown & listbox in my webpage.
I am trying to get a list of CategoryID from a lstCatID listbox i am able to populate the listbox with category name.
If i remember correctly in first attempt my code worked fine, after that i made some change then it stated to always get the first item selected x No. of time
<asp:ListBox ID="lstCatID" runat="server" DataTextField="CategoryName"
DataValueField="CategoryID" SelectionMode="Multiple" CssClass="lstListBox">
</asp:ListBox>
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// Response.Write();
CatID += lstCatID.SelectedItem.Value + ",";
}
}
Response.Write(CatID);
}
I am not sure what is going wrong i checkd MSDN it show exactly the same way of doing it.
May be i am doing something wrong.
Just to add using firefox i am able to see multiple selected value have selected property.
<option value="3" selected="selected">One</option>
<option value="2">Two</option>
<option value="29" selected="selected">Three</option>
<option value="25" selected="selected">Four</option>
<option value="22" >Five</option>
My output in this case will be 3,3,3
I would appreciate help in this regard
I am not sure what is wrong with the logic i am using.
I came across a nice solution using LINQ.
This single statement works great & gets me the desired results.
string values = String.Join(", ", lstCatID.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());
RESULT: 3,29,25
You are setting it to the same value every time:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// you are always using lstCatID.SelectedItem.Value.
CatID += lstCatID.SelectedItem.Value + ",";
}
}
When you actually want the value of the item in your loop that is selected:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// get the value of the item in your loop
CatID += li.Value + ",";
}
}
Try to add Page.IsPostback on your Page_Load like
protected void Page_Load(object sender, EventArgs e)
{
// Do your API code here unless you want it to occur only the first
// time the page loads, in which case put it in the IF statement below.
if (!Page.IsPostBack)
{
}
}
Code:
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected )
{
// TODO: Whatever you are doing with a selected item.
}
}
Response.Write(CatID);
}
Once i was facing the same problem and i made Postback mistake.
Hope it works.
Get the selected items using linq
var selected = lstCatID.Items.Where(i => i.Selected);
Minutes later I found a solution:
If lstLocations.Items.Count > 0 Then
For i As Integer = 0 To lstLocations.Items.Count - 1
If lstLocations.Items(i).Selected Then
'insert command
Dim selectedItem As String = lstLocations.Items(i).Text
End If
Next
End If
This worked fine in my scenario
i have a datalist contains checkboxlist.
<asp:DataList ID="dtlstfilter" runat="server">
<ItemTemplate>
<asp:CheckBoxList ForeColor="Gray" AutoPostBack="true" OnSelectedIndexChanged="chklist_SelectedIndexChanged" ID="chklist"
runat="server">
</asp:CheckBoxList>
</ItemTemplate>
</asp:DataList>
when i check one from the checkbox list in the SelectedIndexChanged event i got the selected value using
CheckBoxList c = (CheckBoxList)sender;
string selectedvalue= c.SelectedValue;
likewise how can get the value from a checkboxlist if i uncheck one from the checkboxlist
The SelectedIndexChanged gets also fired if you uncheck a CheckBox. So it works the same way. But if you want to know the (now) unchecked item(s), you have to store the old selection somewhere, for example in the ViewState:
private IEnumerable<string> SelectedValues
{
get
{
if (ViewState["SelectedValues"] == null && dtlstfilter.SelectedIndex >= -1)
{
ViewState["SelectedValues"] = dtlstfilter.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
}else
ViewState["SelectedValues"] = Enumerable.Empty<string>();
return (IEnumerable<string>)ViewState["SelectedValues"];
}
set { ViewState["SelectedValues"] = value; }
}
protected void chklist_SelectedIndexChanged(Object sender, EventArgs e)
{
CheckBoxList c = (CheckBoxList)sender;
var oldSelection = this.SelectedValues;
var newSelection = c.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value);
var uncheckedItems = newSelection.Except(oldSelection);
}
This should even work if multiple checkboxes can be selected.
You can take the jQuery Route if it suits you...
if (!IsPostBack)
{
foreach (ListItem item in chkList.Items)
{
//adding a dummy class to use at client side.
item.Attributes.Add("class", "chkItem");
}
}
Put one button on your form with style display : none. And a Hidden Field to track the currently checked checkbox.
<asp:Button ID="hdnButton" runat="server" style="display:none;" OnClick="hdnButton_Click"/>
<asp:HiddenField ID="hdnCurrent" runat="server" />
The jQuery Part....
$(".chkItem input:checkbox").change(function(){
$("#hdnCurrent").val($(this).attr("id") + "|" + $(this).attr("checked"));
$("#hdnButton").click();
});
You can use more hidden fields if you don't want to do string operations on backend. Depends on your taste.
Then handle the button click event like below.
protected void hdnButton_Click(object sender, EventArgs e)
{
String[] Value = hdnCurrent.Value.Split('|');
if (Value[1] == "true")
{
//Do operations here when the check box is checked
}
else
{
//Do operations here when the check box is unchecked
}
//Value[0] contains the id of the check box that is checked/unchecked.
}
I have a repeater which dynamically generate tab links using Sitecore (sc:Link) like this:
<asp:Repeater ID="rptTab" runat="server" OnItemDataBound="rptTab_ItemBound">
<ItemTemplate>
<li id= "liTabTest" runat = "server" class="tab-label">
<asp:HyperLink onclick = "javascript: TabClick(this)" runat="server" id="aLink">
<sc:Link ID="hlTabLink" Field="scTabLink" runat="server" ></sc:Link>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
I manipulate the CSS via JS:
var loadURL;
$(document).ready(function () {
init();
});
function init() {
$("ul#Tab-labels li:first").addClass("TabbedPanelsTabSelected");
};
function TabClick(obj) {
$("ul#Tab-labels li").removeClass("TabbedPanelsTabSelected");
$(obj).addClass("TabbedPanelsTabSelected");
};
Unfortunately, this is not working because each tab is a separate .ASPX page, so the page is getting rendered again and that is why Init() in JS is getting called and CSS is getting executed to the first item everytime.
This is my code behind:
protected void rptTab_ItemBound(Object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Item i = e.Item.DataItem as Item;
Link hlTabLink = e.Item.FindControl("hlTabLink") as Link;
hlTabLink.DataSource = i.Paths.FullPath;
hlTabLink.Field = "Title";
HyperLink aLink = e.Item.FindControl("aLink") as HyperLink;
aLink.NavigateUrl = Sitecore.Links.LinkManager.GetItemUrl(i);
}
}
I tried adding CSS through code-behind but it didnt work because I cannot get the index of the tab (which tab is getting selected). Any solution will be appreciated! Thanks!
Don't run javascript for a task that is better (and easier) accomplished in code-behind. Just set the active class for the repeater item where Sitecore.Context.Item matches the name of the tab. Pseudo code inside ItemDataBound:
if(i == Sitecore.Context.Item)
{
HtmlGenericControl li = e.Item.FindControl("liTabTest");
li.Attributes.Add("class","TabPanelTabbedSelected");
}
Not sure if HtmlGenericControl is correct here, or if it has a CssClass property, but I hope you get the idea. If there is no direct representation for li on the server side, you can also bind a string literal or use a Literal control.
The answer to my question is: The repeater is like an array. So I can get the 1st and Last element of a repeater like this:
string currClass = hc.Attributes["class"].ToString();
string count = e.Item.Controls.Count.ToString();
if (e.Item.ItemIndex == 0)
{
currClass += " TabbedPanelsTabSelected";
}
else if (e.Item.ItemIndex.ToString() == count)
{
currClass += " last";
}
In this way I can add a css to my first element and the last element through Repeater.
I have a problem regarding TReeview and combo box.
Problem:
I have a Treeview with Parent and Child Nodes.
I have a drop box or a combo box. Whenever I select a value from the combobox it should automatically select the same node in the treeview list.
Please give me suggestions on how to perform this.
This is what I tried so far:
protected void nav_dd_parent_SelectedIndexChanged(object sender, EventArgs e)
{
nav_treeview.selectedvalue = nav_dd_parent.selectedvalue.tostring();
}
But it says that nav_treeview is read only and it can not be assigned any values.
I just tried the following to give you an example:
HTML:
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Dictionary<string, Int32> myList = new Dictionary<string, Int32>();
myList.Add("Text1", 1);
myList.Add("Text2", 2);
myList.Add("Text3", 3);
myList.Add("Text4", 4);
myList.Add("Text5", 5);
foreach (KeyValuePair<string, Int32> s in myList)
{
this.TreeView1.Nodes.Add(new TreeNode(s.Key, s.Value.ToString()));
this.DropDownList1.Items.Add(new ListItem(s.Key, s.Value.ToString()));
}
foreach (TreeNode tn in this.TreeView1.Nodes)
{
tn.ChildNodes.Add(new TreeNode("Hello World"));
tn.Collapse();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.DropDownList1.SelectedItem != null)
{
foreach (TreeNode tn in this.TreeView1.Nodes)
{
if (tn.Value == this.DropDownList1.SelectedItem.Value)
{
tn.Selected = true;
if (tn.ChildNodes.Count > 0)
{
tn.Expand();
}
}
else {
tn.Collapse();
}
}
}
}
Hopefully this is what you needed. Good luck!
You will want to set AutoPostBack on the DropDownList and add an OnSelectedIndexChanged event handler. Or, you could try and write it all in javascript to avoid the post back.
I have a Listview control "lstStudents" and i have added checkboxes inside the List viewControl.I need to add a Select All check box which results in checking all the checkboxes inside the ListView i use the following code but it doesn't work.
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (Control cont in lstStudents.Controls)
{
if (cont.GetType() == typeof(CheckBox))
{
(cont as CheckBox).Checked = true;
}
}
}
I'm using c# windows Forms......
You are talking to the dataitem instead of the control itself
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in lstStudents.Items)
{
item.Checked = chkAll.Checked;
}
}
the Checked property is always accessible on a ListViewItem, visible or not.
lstStudents.Items returns only ListViewItem
so there is no need for an extra reference validation on these items
Try this:
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListViewDataItem item in lstStudents.Items)
{
CheckBox cbSelect = item.FindControl("cbSelect") as CheckBox;
if (cbSelect != null)
{
cbSelect.Checked = true;
}
}
}
Assuming your listview definition goes something like this:
<asp:listview runat="server">
<itemtemplate>
<asp:checkbox id="cbSelect" runat="server" />
</itemtemplate>
</asp:listview>