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.
}
Related
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();
I have two dropdown lists, where one is populated on page load and the other should only be populated when a value is selected in the first one. The first dropdown list is defined as:
<asp:DropDownList ID = "base_ddl" runat="server" ToolTip="Base" OnSelectedIndexChanged = "BaseSelected">
// snip...
</asp:DropDownList>
Then, the second dropdown list (secondary_ddl) is populated in the OnSelectedIndexChanged method, BaseSelected.
public void BaseSelected(object sender, EventArgs e)
{
if (base_ddl.SelectedValue == "-1")
{
secondary_ddl.Visible = false;
}
else
{
secondary_ddl.Items.Clear();
// extract information to populate dropdown here
// snip.
IList<InfoContainer> info = getInfoBasedOnSelected(base_ddl.Value);
foreach (InfoContainer i in info)
{
secondary_ddl.Items.Add(new ListItem(i.name, i.value));
}
}
}
This doesn't work, which leads to this question: why? How can I dynamically update that dropdown from the OnSelectedIndexChanged function for the other dropdown?
1st set AutoPostBack="True" property of base_ddl
and then
secondary_ddl.Items.Clear();
IList<InfoContainer> info = getInfoBasedOnSelected(base_ddl.Value);
secondary_ddl.DataTextField = "name";
secondary_ddl.DataValueField = "value";
secondary_ddl.DataSource = info;
secondary_ddl.DataBind();
I have an ASPxGridView and in the EditForm, I have a popup form when the suer clicks a button. I need to get the ID for the currently selected entity/row so that I can query the db and populate a dropdown on the popup based on that ID. How can I get that? I know with some events, you can do this:
protected void myGrid_OnRowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
Guid entityId = (Guid)e.Keys[0];
So I wanted to try that with the SelectionChanged event, but the event argument is only of type EventArgs, so i cannot use the above..
Ideas?
You can use the HtmlRowCreated event to bind the contents of the dropdown as shown below.
protected void myGrid_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.EditForm)
return;
var grid = sender as ASPxGridView;
if (grid == null)
return;
var row = (sender as ASPxGridView).GetRow(e.VisibleIndex) as MyEntity;
var ddlMyDropDown = grid.FindEditFormTemplateControl("ddlMyDropDown") as ASPxComboBox;
ddlMyDropDown.DataSource = GetDataForMyDropdown(); // Your Business Logic
ddlMyDropDown.DataBind();
}
I ended up doing something client-side. First, I added this column:
<dx:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0" Width="40">
<HeaderTemplate>
<dx:ASPxCheckBox ID="SelectAllCheckBox" runat="server" ToolTip="Select/Unselect all rows on the page"
ClientSideEvents-CheckedChanged="function(s, e) { gridView.SelectAllRowsOnPage(s.GetChecked()); }" />
</HeaderTemplate>
</dx:GridViewCommandColumn>
then I also added this (to the same grid):
<ClientSideEvents SelectionChanged="grid_SelectionChanged" />
Lastly, the javascript:
var selected = [];
function grid_SelectionChanged(s) {
s.GetSelectedFieldValues("ID", GetSelectedFieldValuesCallback);
}
function GetSelectedFieldValuesCallback(values) {
selected = [];
for (var i = 0; i < values.length; i++) {
selected.push(values[i]);
}
}
How do I determine if the checkbox is checked or not checked?
Very perplexed why this is not working - it is so simple!
On my web form:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" Text="Save" CssClass="publish" />
Code behind which runs in the click event for my save button:
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
When debugging it never steps into the If statement when I have the checkbox checked in the browser. Ideas?!
I think there maybe some other code affecting this as follows...
In Page_load I have the following:
PublishButton.Click += new EventHandler(PublishButton_Click);
if (newsItem.IsDraft == 1)
{
DraftCheckBox.Checked = true;
}
else
{
DraftCheckBox.Checked = false;
}
newsItem is my data object and I need to set the checkbox checked status accordingly.
When the save button is hit I need to update the IsDraft property based on the checked status of the checkbox:
void PublishButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
newsItem.Title = TitleTextBox.Text.Trim();
newsItem.Content = ContentTextBox.Text.Trim();
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
else
{
newsItem.IsDraft = 0;
}
dataContext.SubmitChanges();
}
}
So, isDraft = 1 should equal checkbox checked, otherwise checkbox should be un-checked. Currently, it is not showing this.
Specify event for Button Click
<asp:Button ID="PublishButton" runat="server" Text="Save" onclick="PublishButton_Click" />
What i can see you have not got a OnClick on your button. So like this:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" OnClick="PublishButton_Click"
Text="Save" CssClass="publish" />
And then the function should work like it is:
protected void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
Please replace code as following code..
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked==True)
{
newsItem.IsDraft = 1;
}
}
Try adding onclick="PublishButton_Click" in the button field on the form. And I don't know if it makes a difference, but generated event handlers are protected void.
For me the best solution in the end has been to create 2 separate pages: 1 for editing a news articles & 1 for a new news article. So Ill never then be in the position of a new news data object being created when the page reloads.
Both page return to the article index list page when the save button is pressed and that seems to work with being able to save the state of the draft checkbox and then show the state on the edit page.
The checkbox.checked isn't used in the context you want it to (this is a boolean that if true, will make the checkbox look checked).
What you could do is to use instead a checkboxlist. Then you could do the following:
foreach(Listitem li in CheckBoxList1.Items)
{
if (li.Selected)
{
NewsItem.Isdraft = 1;
}
}
<asp:TemplateField HeaderText="Select One">
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow di in GridView1.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
if (rad.Checked&&rad!=null)
{
s = di.Cells[1].Text;
}
}
Response.Redirect("applicants.aspx?form=" +s);
}
I'm selecting the rows that are selected with this but I have a problem here I want user to be able to select only one radiobutton but its allowing all the radiobuttons to be selected at once.Can you help me in removing this problem please.
please.
Maybe I'm too late here on the party but this will do the trick,
check out here......
This might be useful for someone watching this answer in the future.
In the ASP page you need to set the GroupName property to be the same for all the radio buttons, e.g.:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="RadioGroup" />
well for that you can use follwing code
first of all you should define the groupName.The follwing code will work
<asp:RadioButton ID="RadioButton1" OnCheckedChanged="rbSelector_CheckedChanged" AutoPostBack="true" GroupName="Apply" runat="server"></asp:RadioButton>
C#
protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
{
foreach (GridViewRow oldrow in GridView2.Rows)
{
((RadioButton)oldrow.FindControl("RadioButton1")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("RadioButton1")).Checked = true;
}
You can try this link to select single radiobutton in grid : http://www.c-sharpcorner.com/uploadfile/krishnasarala/select-single-radio-button-in-gridview-in-Asp-Net/
Using the GroupName property by itself won't work, each radio button will still get a unique name attribute since they're in different rows of the grid.
One option is to emit the radio button markup manually using a Literal control (example). This will make it easy to group the radio buttons on the client-side, but requires a bit more work to determine which button was selected on postback.
When I needed this behavior, I found it easier to keep the radio buttons as server-side controls, and just enforce the button group w/ jQuery. Put your RadioButton in a TemplateField as you've shown, then add this code to uncheck all the other buttons when one is checked:
$(document).ready(function () {
// could also pass in a unique ID selector
createManualRadioButtonGroupForGridView(".myGridViewClass");
});
function createManualRadioButtonGroupForGridView(gridViewSelector) {
$(gridViewSelector + " input[type=radio]").change(function () {
var checkedRadioButton = this;
$(gridViewSelector + " input[type=radio]").each(function (e) {
if (this !== checkedRadioButton) {
$(this).prop("checked", false);
}
});
});
}