I have a CheckBox and a CheckBox list on my web page.
If the CheckBox is selected, all the CheckBoxes in the CheckBoxList should get selected, and if the CheckBox is unchecked, similarly all the CheckBoxes in the CheckBox should get deselected (unchecked).
.aspx code
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
<asp:ListItem Selected="True">Item D</asp:ListItem>
<asp:ListItem>Item E</asp:ListItem>
<asp:ListItem>Item F</asp:ListItem>
<asp:ListItem>Item G</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allChkBox" Text="Select all" runat="server"
oncheckedchanged="allChkBox_CheckedChanged" />
I tried by doing somehting like this, but it didb't work:
bool prevSelection = false;
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
if (!prevSelection)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = true;
}
}
else
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = false;
}
}
prevSelection = !prevSelection;
}
I prefer to use client script for something like this so your page doesnt have to do a postback
If that is a possibility try firing a javascript function on click to do the looping and selecting ... something like
<script type="text/javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
if(aa.elements[i].type == 'checkbox') {
aa.elements[i].checked = checked;
}
}
}
</script>
It's been a while since I've dabbled in ASP.NET, but your prevSelection field will be initialized to false on each and every request. That value will not be persisted between requests. So, you either need to store it in View State or the cache and load it from there in your event handler, or, even better, change your method to something like this:
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = allChkBox.Selected;
}
}
How about this Iif I have understood the requirement right!)? This will make all items selected in a CheckBoxList control by default when it renders:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
LoadCountryList();
}
private void LoadCountryList()
{
_ctx = new PayLinxDataContext();
chkCountries.DataSource = _ctx.Countries.OrderBy(c => c.Name);
chkCountries.DataBind();
foreach (ListItem item in chkCountries.Items)
{
item.Selected = true;
}
}
Instead of using a variable outside the function, how about using the checkbox itself:
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkbox = sender;
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = chkbox.Selected;
}
}
you can do it with linq like this
var allChecked = (from ListItem item in CheckBoxList1.Items
where item.Selected
select int.Parse(item.Value)).ToList();
var all = (from ListItem item in CheckBoxList1.Items
select int.Parse(item.Value)).ToList();
function CheckUnCheckAll()
{
var list = document.getElementById("<%=DataList1.ClientID%>") ;
var chklist = list.getElementsByTagName("input");
for (var i=0;i<chklist.length;i++)
{
if (chklist[i].type=="checkbox" )
{
chklist[i].checked = checkoruncheck;
}
}
}
Related
I am trying to reference a non-asp check box in C# code behind. The reason the checkbox is not an asp element, is it gets auto-generated on the fly, rather than being a part of the website. So far I have the following relevant aspx:
<asp:Table ID="myTable" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>A</asp:TableCell>
<asp:TableCell>B</asp:TableCell>
<asp:TableCell>C</asp:TableCell>
<asp:TableCell>D</asp:TableCell>
<asp:TableCell>E</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:LinkButton runat="server" ID="TEST" CssClass="btn btn-default pull-right" OnClick="TEST_Click">
TEST <i class="m-icon-swapright m-icon-white"></i>
</asp:LinkButton>
And the C# code behind is:
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
if (check)
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" >";
}
else
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" checked>";
}
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
HtmlInputCheckBox chkbox = (HtmlInputCheckBox)FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
MessageBox.Show("NOTHING :(");
}
chkbox is always null :(.
You'll need to change two things.
In order to find a checkbox via FindControl it must be part of the pages control collection, which means you have to add a CheckBoxcontrol.
CheckBox c = new CheckBox { ID = "chk" + i };
tempCell.Controls.Add(c);
The dynamically added CheckBox control is part of the control collection of the Table, so you'll have to search for it there instead of on the page.
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
Below you find a full update of your code.
protected void Page_Load(object sender, EventArgs e)
{
GenerateTable();
}
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
CheckBox c = new CheckBox { ID = "chk" + i };
c.Checked = check;
tempCell.Controls.Add(c);
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
{
MessageBox.Show("NOTHING :(");
}
}
I have a checkbox that I have declared in the following manner
checkbox = new CheckBox();
checkbox.ID = "AreaGroup";
checkbox.AutoPostBack = true;
checkbox.CheckedChanged += new System.EventHandler(this.EHArea_Clicked);
I then declare the EHArea_Clicked function in the code behind with the following method
void EHArea_Clicked(Object sender, EventArgs e)
{
foreach (RepeaterItem aItem in Repeater1.Items)
{
checkbox = (CheckBox)aItem.FindControl("TownCheckbox");
if (((CheckBox)sender).Checked)
{
checkbox.Checked = true;
}
else
{
checkbox.Checked = false;
}
}
}
The problem I have is that
((CheckBox)sender).Checked
Always evaluates to true regardless of if I am checking or unchecking the checkbox. Does anyone have an idea as to why this is happening?
I believe your prolbem is that you are reusing the checkbox variable. You need a new variable. Try something like this. Also you can reduce the if else to one line.
void EHArea_Clicked(Object sender, EventArgs e)
{
foreach (RepeaterItem aItem in Repeater1.Items)
{
CheckBox currentCheckBox = (CheckBox)aItem.FindControl("TownCheckbox");
currentCheckBox.Checked = ((CheckBox)sender).Checked;
}
}
i have CheckChanged event behind Checkbox, it is called whether i tick or un-tick checkbox but i only wat to call this event when check box is checked not on uncheck.
code:
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
HiddenFieldShowHideButtons.Value = "True";
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
This alternate might work
<asp:CheckBox ID="CheckBox1" runat="server" Text="Check"
AutoPostBack="True" OnClick="return chkSelected();"
OnCheckedChanged="CheckBox1_CheckedChanged" />
<script type="text/javascript">
function chkSelected() {
var chk = document.getElementById('<%= CheckBox1.ClientID %>');
if (chk.checked) {
__doPostBack('<%= CheckBox1.ClientID %>', '');
} else {
return false;
}
}
</script>
You can use an if condition to check the state of the Checked property of the CheckBox control. As the following:
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (chkIsHead.Checked)
{
// put your code here
}
}
I have populated my checkboxlist on the fly via callback like this:
<dx:ASPxComboBox ID="ASPxComboBox_Prot" runat="server" DataSourceID="SqlDataSource_Prot"
TextField="LIBELLE" ValueField="NO_PROT" ValueType="System.Int32">
<ClientSideEvents SelectedIndexChanged="function(s, e) { cbp_ProtOrdos.PerformCallback(s.GetValue());}" />
</dx:ASPxComboBox>
</td>
</tr>
</table>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel_ProtOrdo" runat="server"
ClientInstanceName="cbp_ProtOrdos" OnCallback="cbp_ProtOrdo_Callback">
<PanelCollection>
<dx:PanelContent>
<dx:ASPxCheckBoxList ID="CheckBoxList_Ordo" runat="server" ClientInstanceName="CheckBoxList_Ordo" ValueType="System.Int32" TextField="LIBELLE" ValueField="NO_ORDO">
</dx:ASPxCheckBoxList>
<dx:ASPxButton ID="ASPxButton_ProtOrdoGen" runat="server"
Text="Générer ordonnance & Planifier pour infirmier"
OnClick="ASPxButton_ProtOrdoGen_Click"
EnableDefaultAppearance="false" BackColor="Yellow" CssClass="bt" Theme="BlackGlass" ForeColor="Black">
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And on server side code:
protected void cbp_ProtOrdo_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
var panel = sender as ASPxCallbackPanel;
var cblist = panel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
cblist.DataSource = Outils.Get_ProtOrdo(ASPxComboBox_Prot.Value.ToString());
cblist.DataBind();
}
It works fine, but now I want to get the value that had been checked by the user. So I add the button to do that.
protected void ASPxButton_ProtOrdoGen_Click(object sender, EventArgs e)
{
//TabPage oPage = ASPxPageControl_DosSoin.TabPages.FindByName("Surveillance");
//ASPxPanel oPanel = (ASPxPanel)oPage.FindControl("ASPxPanel_ListSurveil");
//ASPxRoundPanel oRoundPnl = (ASPxRoundPanel)oPanel.FindControl("ASPxRoundPanel_ProtOrdo");
//ASPxCallbackPanel ocbpPanel = (ASPxCallbackPanel)oRoundPnl.FindControl("ASPxCallbackPanel_ProtOrdo");
//ASPxCheckBoxList cblist = (ASPxCheckBoxList)ocbpPanel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
List<string> selectItems_Ordo = new List<string>();
foreach (var oItem in CheckBoxList_Ordo.Items)
{
ListEditItem oNewChk = (ListEditItem)oItem;
if (oNewChk.Selected)
{
selectItems_Ordo.Add( oNewChk.Value.ToString());
}
}
foreach (var oItem in selectItems_Ordo)
{
if (DossierDuSoins.check_doublon_ordo(oItem.ToString(), Soin_Id) == 0)
DossierDuSoins.RamenerVal(DossierDuSoins.GetLibOrdo(oItem.ToString()), Soin_Id, oItem.ToString());
}
string TempId = "";
if (selectItems_Ordo.Count == 0)
{
lbl_err.Text = "Pas de médicament de sélectionné";
}
else
{
foreach (string selectItemId in selectItems_Ordo)
{
if (TempId != "")
TempId += ",";
TempId += selectItemId.ToString();
}
string AdrUrl = "Print_Ordo.aspx?SoinId=" + Soin_Id + "&SelId=" + TempId;
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
}
}
The problem is that I can not get my checked value. Is that because the postback destroys all checkboxlists that I had constructed on the fly ?
Try this instead of using vars for selecting your checkbox list
foreach (ListItem yourItem in YourCheckBoxList.Items)
{
if (item.Selected)
{
// If the item is selected, Add to your list/ save to DB
}
else
{
// If item is not selected, do something else.
}
}
i try to send email in asp.net .when admin select checkbox then he/she able to send mail to respective email id and email is also store in database in userss table ..but when i build the code it shows me error
code is
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkAll =
(CheckBox)Repeateremail.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in Repeateremail.Items)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
}
}
else
{
foreach (GridViewRow gvRow in Repeateremail.Items)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
}
}
}
in this line
CheckBox chkAll =
(CheckBox)Repeateremail.HeaderRow.FindControl("chkSelectAll");
it show me error in header
error
'System.Web.UI.WebControls.Repeater' does not contain
a definition for 'HeaderRow' and no extension method 'HeaderRow'
accepting a first argument of type 'System.Web.UI.WebControls.Repeater'
could be found (are you missing a using directive or an assembly
reference?)
where as in html i use like this in header template
<td>
Check
<asp:CheckBox ID="chkSelectAll" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged"/>
Send Mail To All ?
</td>
and in item template
<td>
<asp:CheckBox ID="chkSelect" runat="server"/>
</td>
You do not need to use the FindControl() method, because you are handling the click event for the control you want check property values of anyway, try this instead:
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
// Cast the sender to a CheckBox type
CheckBox chkAll = sender as CheckBox;
// The as operator will return null if the cast is not successful,
// so check for null before we try to use it
if(chkAll != null)
{
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in Repeateremail.Items)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
}
}
else
{
foreach (GridViewRow gvRow in Repeateremail.Items)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
}
}
}
}