Asp.net CheckBox within GridView looses its value - asp.net

I have a GridView which has bound fields and a template field for checkbox. I wrote a code for deletion of records as per checking checkboxes. My problem is
HtmlInputCheckBox chk;
foreach(GridViewRow dr in dgvdetails.Rows)
{
chk = (HtmlInputCheckBox)dr.FindControl("ch");
chk.Checked = true;
if (chk.Checked)/// **here checkbox is not checked even if I'm check it**
{
pl.id = int.Parse(chk.Value);
bl.deletedgvdetails(pl);
}
}

There are two things that come to mind that could be at play here. I'm not sure when your code is running - with regard to the page lifecycle - but if it is being handled in a button click event you may want to make sure that your grid view has not been "rebound" during a page event such as Page_Load which runs prior to button click events firing. IF this is the case, all of your check boxes will have been reinitialized before your delete method runs.
Secondly, inside your foreach loop you may want to pay attention to the RowType of the current row. The first iteration through the loop may be focusing on the Header Row (if you have it enabled for the GridView) and therefore may not have the checkbox.
Checking that if(chk != null) {} is always a good idea if you use e.Row.FindControl() - just in case.

Related

ASP.NET - How to remove dynamically added Gridviews from Asp:Panel

I am populating an Asp:Panel with gridviews generated dynamically based on user selection. As the user changes the selection criteria and the date, the panel to show the new gridviews based on the search criteria. I am doing MyPanel.Controls.Clear(), but the gridviews are still showing the old result. Then i tried the following, but still of no use, the panle is always showing the first result.
foreach (Control c in MyPanel.Controls)
{
if (c is GridView)
{
MyPanel.Controls.Remove(c);
//Response.Write("**"+c.ID);
}
// else
// Response.Write("##" + c.ID);
}
Response.Write("cnt=" + MyPanel.Controls.Count ); // Always showing as 1 even when the count is greater than 1.
Any idea how i can clean the panel each time before i try to populate the panel with new results as gridviews?
ray..
Why you are generating panel each time make one or two panel as you required and just change their content or set visible hide true or false as you required creating panel each time is not a good approach.

Why are my ASP.NET checkboxes always false?

I'm working on a ASP.NET web forms application. I have a four-column listview, bound to a datasource on pageload(), populated with contact names. One of the columns contains a checkbox. Users select a checkbox to indicate the corresponding contact should be processed in the next step.
The form also contains a button. When this button is clicked, the following code runs to process the selected contacts.
foreach (var x in lvPeople.Items)
{
chkSelected = (CheckBox)x.FindControl("IsLetterRecipient");
if (chkSelected.Checked)
{
// the person was selected by the user, do stuff here...
}
}
When I set a breakpoint on the line containing the IF statement, the breakpoint gets hit seven times (once for each row in the listview == seven checkboxes). However, the code inside the IF block never runs because .Checked is always False, regardless of the whether or not the checkbox is actually checked.
AutoPostBack, on the checkbox, is set to False. EnableViewState on the checkbox and listview is set to True.
What am I doing wrong? How do I get the .Checked status of the checkboxes?
Probably, when you bind the data on Page_Load you forgot to do:
if(!IsPostBack)
{
//bind the data to the list
}

Confirm DropDownList selected value

I want to show the user a confirm dialog when he tries to change the selected item of a DropDownList. If the selection is confirmed i want to execute some server side code.
Say, DDL has values 1 and 2.
Value 1 is selected (default).
The user selects Value 2. A confirm dialog appears.
If the user selects 'Yes', then the selected item changes. Some server side code must be executed.
If the user selects 'No' then the selected item is reverted back to Value 1. No server side code executed.
I'm having a lot of trouble with this one, since DDL has few events to use.
So far i got
this.MyDropDown.Attributes["onChange"] = #"return confirm('Are you sure?');";
and a event handler for the SelectedIndexChanged event of the DDL for the server side code.
But i'm having trouble with the fact that i can't neither stop (or revert) the item being changed nor the SelectedIndexChanged event being fired.
Any suggestions?
The reason it's not triggering the server side event is because you're wiping out the built-in webforms event handler that would trigger the post back. As for reverting the value, you'll need to save it and then reload it.
add this javascript function
function handleChange(opt) {
if (!confirm('are you sure')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
and set the client side events like so
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
This is complete solution, as i have already used it. Just refer the following instructions:
// Paste it in Aspx file
function handleChange(opt) {
if (!confirm('Are you sure?')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
Paste this in Page Load event outside IsPostBack:
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
Note: Set AutoPostBack Proerty False of Dropdownlist.

Getting Checked rows from gridview in asp.net

I have a GridView in ASP.net where I have a CheckBox column. The user can toggle the CheckBox. Now, what I want is that when the user clicks on a button, all the records from the GridView where the CheckBox is checked should be displayed. And on another button, the opposite state should be displayed...
I am not getting the logic for the same.
Can anyone please help me with the logic..
You could iterate through the GridViewRows and check if the CheckBox is checked using something like the following
Edit from comments, fixed small bugs. Thanks guys. (3/20/2013):
foreach (GridViewRow row in yourGridViewID.Rows)
{
CheckBox check = (CheckBox)row.FindControl("CheckBoxName");
if (check.Checked)
{
//Take Row information from each column (Cell) and display it
}
else
{
//Display in seperate area
}
}
The index is going to be the column number starting from 0, going left to right of which column holds the CheckBox. You need to make sure the CheckBox has an ID name which is used at CheckBoxName. If you don't have an ID for that, you can also use
CheckBox check = (CheckBox)row.Cells[index].Controls[0];

Set HTML input checkbox name in listview

I am trying to add a checkbox in a listview with value as ids of the records from the database so I can allow the user to check the ones they want to delete and when they click the delete button I can get value collection of checkbox with request.form.
My problem is, because checkbox in a listview ASP.NET renders the listview name into the name property of the checkbox, it prevents me to do request.form["checkboxname"].
I don't want to use Listviews delete commands but simply use request.form to get the collection of checked values.
How can I set name of the htmlinput checkbox so .NET doesn't change it in render time?
I have tried:
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
HtmlInputCheckBox _CheckBoxDelete = (HtmlInputCheckBox)e.Item.FindControl("CheckBoxDelete");
_CheckBoxDelete.Visible = true;
_CheckBoxDelete.Value = DataBinder.Eval(dataItem.DataItem, "id").ToString();
_CheckBoxDelete.Name = "deletechecked";
But still it renders like:
<input name="PmList$ctrl0$CheckBoxDelete" type="checkbox" id="PmList_ctrl0_CheckBoxDelete" value="3" />
This is happening because ListView is a Naming Container. You can get around this in a couple of ways, but they all boil down to the choice of:
Rendering the HTML you want.
Pulling out the checked items in a different way.
The former is doable, but you'll likely loose a lot of ASP.NET's built in functionality. I'd advise against it unless you're deeply familiar with the control life cycle.
You've got everything you need for the pulling the values out in a way ASP is expecting:
HtmlInputCheckBox _CheckBoxDelete = (HtmlInputCheckBox)item.FindControl("CheckBoxDelete");
You just need to wait for the control hierarchy to be populated, and then loop over the ListView.Items looking for the checkboxes. Your "Delete" button's event handler is probably a good place to call this from.
Incidentally, why are you using a HtmlInputCheckbox, rather than a CheckBox?
I have sorted it out with:
string idCollectionTodelete = string.Empty;
foreach (string x in Request.Form)
{
if (x.IndexOf("CheckBoxDelete") > -1)
{
idCollectionTodelete += Request.Form[x] + ",";
}
}
new DB().DeleteUserPm(
ActiveUsername(), subdomain, idCollectionTodelete.TrimEnd(','));
It is not an ideal solution but it does work for me.
I do this
List<HtmlInputCheckBox> chkDeleteContacts = new List<HtmlInputCheckBox>();
foreach (RepeaterItem item in rptrFamilyContacts.Items)
{
chkDeleteContacts.Add((HtmlInputCheckBox)item.FindControl("chkDeleteContact"));
}
foreach(HtmlInputCheckBox chkDeleteContact in chkDeleteContacts)
{
//Delete Contact
if(chkDeleteContact.Checked)
blnStatus = BusinessUtility.DeleteConsumerContact(LoginConsumerID, chkDeleteContact.Value);
}
Slightly easier in my opinion

Resources