I am having one gridview and check box for each row of gridview and one button outside gridview.
If I click on button then it should check for atmost one checkbox should be checked, otherwise it will display a message and return from loop.
But how to get the checkbox selected length in gridview in serverside.
If you just want to check if there is a checkbox checked in the gridview you can do this in the button:
bool isChecked = theGridview.Rows
.Cast<GridViewRow>()
.Any(a => ((CheckBox)a.FindControl("yourCheckbox")).Checked);
Do not forget using System.Linq;
You need to loop trough the row of the gridview and look for the checkbox as follows
foreach (GridViewRow r in YourGridView.Rows)
{
foreach(string cnt in controls){
int value = Convert.ToInt32(((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Value);
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Checked;
//now you have id and checked/unchecked. use your query to save it to database
}
}
Manipulate this according to you requirement.
foreach (GridViewRow gvrow in final.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
//Perform action 1
}
else
{
// perform action-2
}
Related
So, I have a checkbox1 added dynamically in a modal bootstrap and this has an CheckedChanged event that add some checkbox's ("checkbox1.1" "checkbox1.2" "checkbox1.3"),dynamically as well, so my question is, when I postback (on a submit or link button) how can I know if my checkbox1.1 is checked or not? I can actually know if my checkbox1 is checked or not because i recreate the controls on every postback but the checkbox1.1 i cant because its always depending if my checkbox1 is checked or not. Is there a way i can get it without recreating the checkbox1.1 in my postback ? (without using javascript if possible).
I already tried , Lists, Disctionary, Sessions, Viewstates it seams like if i dont recreat the controls (checkbox1.1) i cant save them and they will be lost
foreach (DataRow item in dt.Rows)
{
i++;
CheckBox chk = new CheckBox();
chk.Attributes["class"] = "mycheckbox";
chk.Font.Name = "Tahoma";
chk.Attributes.Add("runat", "server");
chk.Text = item[descricao].ToString();
//If true add checkbox id = checkbox1
if (divsname.ID == "DadosIdentificacao")
{
chk.ID = checkbox + i;
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(this.chkEventos);
}
//Else checkboxid = checkbox1.1
else
{
chk.ID = checkbox + item[descricao].ToString() + i;
}
divsname.Controls.Add(chk);
ListData.Add(chk);
}
I can get if checkbox1 is checked or not but my checkbox1.1 control disappear on postback.
Solved by instead of creating my checkbox dynamically, fill a Session["list"] with all my checkbox and then creat a new list List List1 = Session["list"] as List and work with that same List1 by hiding or showing my checkbox.
I have a requirement to loop through all checkboxes in ASP.Net page and determine the ID of the checkbox and process a logic if this is checked. Any pseudo code will help. Regards - Yagya
Use the ControlCollection of the form to loop through
foreach (Control ctl in Form.Controls)
{
if (ctl is CheckBox)
{
CheckBox chk = (CheckBox)ctl;
// Process chk as you wish
}
}
If you wish to check within any containers (panels etc), write the code in a recursive function like this one
void CheckControls(ControlCollection collection)
{
foreach (Control ctl in collection)
{
if (ctl is CheckBox)
{
CheckBox chk = (CheckBox)ctl;
//
}
if (ctl.Controls.Count > 0)
CheckControls(ctl.Controls); // Step into the container & check inside
}
}
Call the CheckControls with the Form's control collection
CheckControls(Form.Controls)
& it will step into all containers as well
I have a data bound GridView control, in which I am able to disable individual cells based on the User role. This only works on the first page.
private void LimitAccessToGridFields()
{
if (User.IsInRole("Processing")) return;
foreach (GridViewRow gridViewRow in gvScrubbed.Rows)
{
var checkBox = ((CheckBox) gridViewRow.FindControl("cbScrubbed"));
checkBox.Enabled = false;
// ButtonField does not have an ID to FindControl with
// Must use hard-coded Cell index
gridViewRow.Cells[1].Enabled = false;
}
}
I call this method on Page_Load, where it works. I've tried it in the PageIndexChaging and PageIndexChanged event handlers, where it doesn't work. While debugging, it appears to successfully set Enabled to false in both of the controls in the row. My goal is to disable these fields, depending on user role, after changing the page. How should this be accomplished?
You do not need to iterate through any controls to disable or hide/visible them.
Every cell in a GridView control is actually a HTML table reference, when rendered (look at the code in your page using FireFly or Inspector).
So why not iterate through all the cells, and any controls found within each cell, just disable them? Or you can simply loop through each row of your GridView and disable or hide it directly, which will affect everything inside the row.
Hiding using a Table Cell reference example:
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
tblCell.Enabled = false;
}
}
So that will disable everything table cell by table cell.
OR.. why not just disable the entire row?
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
gRow.Enable = false;
}
If you need to pin-point or filter particular control types (CheckBox, TextBox, Label, etc) and only affect those controls then simply test for them!
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
if (((TextBox)tblCell) != null)
((TextBox)tblCell).Enable = false;
}
}
I found that this must be done in the RowDataBound event handler.
if (e.Row.RowType == DataControlRowType.DataRow)
{
// details elided ...
// Limits the access to grid fields.
if (!User.IsInRole("PROCESSING"))
{
cbstuff.Enabled = false; // a checkbox
e.Row.Cells[1].Enabled = false; //a link button
}
}
I am currently facing a problem. How to get the latest selected value from a asp.net checkbox list?
From looping through the Items of a checkbox list, I can get the highest selected index and its value, but it is not expected that the user will select the checkbox sequentially from lower to higher index. So, how to handle that?
Is there any event capturing system that will help me to identify the exact list item which generates the event?
If I understood it right, this is the code I'd use:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
int lastSelectedIndex = 0;
string lastSelectedValue = string.Empty;
foreach (ListItem listitem in CheckBoxList1.Items)
{
if (listitem.Selected)
{
int thisIndex = CheckBoxList1.Items.IndexOf(listitem);
if (lastSelectedIndex < thisIndex)
{
lastSelectedIndex = thisIndex;
lastSelectedValue = listitem.Value;
}
}
}
}
Is there any event capturing system that will help me to identify the exact list item which generates the event?
You use the event CheckBoxList1_SelectedIndexChanged of the CheckBoxList. When a CheckBox of the list is clicked this event is called and then you can check whatever condition you want.
Edit:
The following code allows you to get the last checkbox index that the user selected. With this data you can get the last selected value by the user.
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = string.Empty;
string result = Request.Form["__EVENTTARGET"];
string[] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (CheckBoxList1.Items[index].Selected)
{
value = CheckBoxList1.Items[index].Value;
}
else
{
}
}
Below is the code which gives you the Latest selected CheckBoxList Item.
string result = Request.Form["__EVENTTARGET"];
string [] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (cbYears.Items[index].Selected)
{
//your logic
}
else
{
//your logic
}
Hope this helps.
Don't know about you, but as a user i wouldn't want the page to post back every time a checkbox item was checked.
This is the solution i would go with (jQuery):
Declare a server-side hidden field on your form:
<asp:HiddenField ID="HiddenField1" runat="server" EnableViewState="true" />
Then wire up client-side event handlers for the checkboxes to store checkbox clicked:
$('.someclassforyourcheckboxes').click(function() {
$('#HiddenField1').val($(this).attr('id'));
This is a lightweight mechanism for storing the ID of the "latest" checkbox clicked. And you won't have to set autopostback=true for the checkboxes and do an unecessary postback.
You dont HAVE to use jQuery - you can use regular Javascript, but, why do more work? =)
Then when you actually do the postback (on a submit button click i assume), just check the value of the hidden field.
Unless of course you WANT to postback on every checkbox click, but i can't envision a scenario in which you'd want this (maybe you're using UpdatePanel).
EDIT
The HTML of a checkbox list looks like this:
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike
So, you can access three things:
Vehicle = $(this).attr('name');
Bike = $(this).attr('value');
I have a bike = $(this).html();
If you're trying to access the databound value, try the second technique.
Give that a try.
I have a asp.net checkbox list bound to a linq to sql datasource and when I check the item count of my CheckBoxList on the page load event it is 0. I want to be able to set the selected items on my checkboxlist here but cannot.
The datasource's selected event fires after the page load. If this is the case, how can I set the selected items on my list?
If I set the SelectedValue to a value it only displays the last value as selected instead of all the values which are selected. How can I select multiple values in my checkboxlist in the pageload event?
I know this is an old post but I had the same problem recently.
To select multiple items of a DataBound CheckBoxList, handle the DataBound event and loop through the Items collection setting the Selected property individually on each item as required.
Setting the SelectedValue property of the control only checks the final item.
foreach (ListItem item in MyCheckBoxList.Items)
{
item.Selected = ShouldItemBeSelectedMethod(item.Value);
}
Nice method I use:
private void SetCheckBoxListValues(CheckBoxList cbl, string[] values)
{
foreach (ListItem item in cbl.Items)
{
item.Selected = values.Contains(item.Value);
}
}
public void SetValueCheckBoxList(CheckBoxList cbl, string sValues)
{
if (!string.IsNullOrEmpty(sValues))
{
ArrayList values = StringToArrayList(sValues);
foreach (ListItem li in cbl.Items)
{
if (values.Contains(li.Value))
li.Selected = true;
else
li.Selected = false;
}
}
}
private ArrayList StringToArrayList(string value)
{
ArrayList _al = new ArrayList();
string[] _s = value.Split(new char[] { ',' });
foreach (string item in _s)
_al.Add(item);
return _al;
}
Thanks,
slnavn2000
Sounds like a Page Lifecycle - Databinding question.
You should really take a look at (the answers to) this question.
I used the DataBound event to select to set the selected items.
set checkboxlist selected items from a list:
List<int> yourlist;
//fill yourlist
foreach (ListItem item in checkboxlist.Items)
{
if (yourlist.Contains(int.Parse(item.Value.ToString())))
item.Selected = true;
}
Lets say your values are string array. Then I would do it this way
foreach (ListItem li in ctrl.Items)
li.Selected = Array.Exists(values, x => x == li.Value);