CheckBox Check is not Working on server side in Gridview - asp.net

I am facing issue in Gridview Check box checked and server side checkbox is showing checked = false.
Its really strange and I haven't seen yet before.
I have written following code.
<script type="text/javascript">
function SelectAll() {
if ($('.SelectAll input:checkbox').attr("checked"))
$('.chkTechs input:checkbox').attr("checked", true);
else
$('.chkTechs input:checkbox').attr("checked", false);
}
function SetCheckBoxes(item) {
//$(item).attr("target").checked // this is to find which element clicked
if ($('.chkTechs input:checkbox').filter(":not(:checked)").length > 0) {
$('.SelectAll input:checkbox').attr("checked", false)
}
else {
$('.SelectAll input:checkbox').attr("checked", true)
}
}
</script>
Server side Button Click
foreach (GridViewRow row in gvList.Rows)
{
CheckBox Checked = (CheckBox)row.FindControl("chkSelect");
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
}

The state of server controls is maintained in viewstate and changing the state of control like you are changing the checked status of checkbox with client script (javascript) is not updated in viewstate. So when you access the control on server side you do not get the changes. You have to store the changes in some hidden field and use that hidden field on server side to update your controls. It is the way asp.net implements the viewstate.

You have to get their value by checking the existence of Request.Form[xxx] parameter of the corresponding checkbox. In you case [chkSelectXXX].
1) Append something meaningful to the ID of your checkbox while creating it. Ex: the primary key val so that the ID of the checkbox should be [chkSelect_PKValue1]
2) On server side loop through Request.Form variables and check for the existence of variables that have the key value starting with chkSelect. Something like this:
foreach(var x in Request.Form)
{
if(x.StartsWith("chkSelect"))
{
//3. Then this checkbox is selected you should parse the
//PK value and do what's necessary.
}
}

Related

Persist checkbox in gridview while custom paging

I have a created a gridview and added a checkbox in item template. This grid has few columns along with DataKey (primary key). Due to performance gain, this grid will fetch the next set of recrods on each page change based on the page number click. So that is done.
Now when user selects a checkbox in page one and then go to page 2 and coming back to page one, then user will not see the checkbox checked as the user did earlier.
So is there a good way to persist the checkbox when user move page to page?
This checkbox be used as a flag to select the rows that can be deleted later by a button outside the grid.
Since you receive a new set each time a paging is selected, I suggest the following approach:
Create an array[] object via javascript that will add to list the datakey whenever a checkbox is selected and in turn remove it if the checkbox is deselected. Something like this:
var selectedDataKeys = [];
$('.checkboxclass').on('change', function() {
// Considering you assign the data key as id for the checkbox otherwise implement a way to retrieve the id.
var dataKey = $(this).prop('id');
// Determine if the dataKey is in the selected data keys array
var isContained = (selectedDataKeys.indexOf(dataKey) > -1 );
if($(this).is(':checked')) {
// If is contained is false - add to the array
if (!isContained)
selectedDataKeys.push(dataKey);
} else {
// If is contained is true - remove to the array
if (isContained){
selectedDataKeys = $.grep(selectedDataKeys, function(value) {
return value != dataKey;
});
}
}
});
From this point on the client user will have an active list of selected items, now its up to you to use that list to manipulate your grid display page. Either modify the display on document ready by comparing all the item on the grid display with the selectedDataKeys array or sending those keys and do the comparison server side.
Hope this helps.

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.

asp.net how to store text box values(tables) thru postbacks

I have created a dynamic matrix display using asp:table/cell combination. and added a textbox displaying a value in each cell. at this point i am creating a view state, which sto res the complete table.
Now if i update the text boxes and click on save, i get the empty table(because of postback) and also the values in ViewState are stale - they are not the updated user values.
so is there a way to create a view state on each text box change. how can i store the edited textbox values?
You do not need to store the text boxes values because they all ready posted back.
You only need to read them from the post back.
Request.Form[YourTextBox.UniqueID]
Now if you wish to save them on viewState you can use a code like
string YouData
{
set
{
ViewState["cYouData"] = value;
}
get
{
if (ViewState["cYouData"] != null)
return ViewState["cYouData"].ToString();
else
return string.Empty;
}
}
But the only reason to do that is to understand if something has change, and to find if something has change a simple hash can do the work.
Detect the PostBack and re-load the values there:
if (!Page.IsPostBack)
{
// initial load
}
else
{
// postback
}

How can I get value from radio-button inserted into innerHtml

I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.

asp.net hidden field not setting new value, need disabled alternative

I have a hidden field on my page
<input runat="server" type="hidden" id="selectedIndex" />
and it is being set by this bunch of code, an onclick event to a gridview's row:
var gridViewCtlId = '<%=GridView.ClientID%>';
var selectedIndex = '#<%=selectedIndex.ClientID%>';
var itemVisible = '<%=ItemVisible.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
var previousRowIndx = null;
window.onload = function showQuery()
{
if ($(selectedIndex).val() != undefined)
{
if ($(selectedIndex).val() != '')
{
var prevRowID = $(selectedIndex).val();
var prevRow = getSelectedRow(prevRowID);
prevRow.style.backgroundColor = '#1A8CD4';
}
}
}
function getGridViewControl(rowIdx)
{
if (gridViewCtl == null)
{
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowSelected(rowIdx)
{
if (document.getElementById(gridViewCtlId).disabled == false)
{
var selRowCCA = getSelectedRow(rowIdx);
if (curSelRow != null)
{
var previousRow = getSelectedRow(previousRowIndx);
var CountIdx = previousRowIndx % 2;
if (document.getElementById(itemVisible) == null)
{
if (CountIdx == 0)
{
previousRow.style.backgroundColor = 'Silver';
}
else
{
previousRow.style.backgroundColor = 'White';
}
}
}
if (null != selRow)
{
previousRowIndx = rowIdx;
curSelRow = selRow;
selRow.style.backgroundColor = '#1A8CD4';
}
}
}
function getSelectedRow(rowIdx)
{
getGridViewControl(rowIdx);
if (gridViewCtl != null)
{
$(selectedIndex).val(rowIdx);
return gridViewCtl.rows[rowIdx];
}
return null;
}
This is what happens: When The page first loads, the hidden field is undefined, which it should be. When I click on a row and then click the 'select' button which then calls this:
GridView.Attributes.Add("disabled", "true");
The gridview becomes disabled (along with the select button) and another gridview comes up (which should happen depending on what is seleted in the first gridview). So now, here is the problem. When I click on a row in the gridview (I'm only talking about the initial gridview, not the secondary one which comes up, that's not an issue here), and click select, everything gets greyed out and most of the time, the selected row will highlight when the page loads (the other times for some reason it defaults to row #2). Then, say you click on row 4 then click on row 1 and then click select, for some reason row 4 will remain highlighted and row 4's data will then populate the second gridview, like you never clicked row 1. But if I click row 4 then click row 1 then click row 1 again, does it save. Does anyone know why that happens?
Also, I'm pretty much trying to disable the first gridview when select is hit so I do
GridView.Attributes.Add("disabled", "true");
rather than
GridView.Enabled = false;
If a user re-clicks the search button (another button located previously on the page which makes this gridview become visible), I would like the secondary gridview to become hidden, and the primary gridview (this one in question) to become re-enabled. But doing
GridView.Attributes.Add("disabled", "false");
when the search button is fired only disables the gridview, which is very weird. Now I know that the disabled field is not supported by any other browser except IE, and i only use it because I need to check if the gridview is disabled so a user cant click on another row after they've made their selection (which happens if I dont do the following:
if (document.getElementById(gridViewCtlId).disabled == false)
So could anyone let me know of another way of accomplishing that task? Thanks again in advance.
Some bits of info on disabled:
Browsers won't send any disabled control's value to the server. This is by definition.
Disabled field is supported by other browsers, but it uses a different model. Note list of supported browsers: http://www.w3schools.com/tags/att_input_disabled.asp (also how it is defined disabled='disabled').
Also see how it compares to the read-only: http://www.w3.org/TR/html401/interact/forms.html#h-17.12.2
Also note according to the standard its support its limited to certain elements. This is important, as you are applying it at an unsupported html element, which is also a likely cause of it not working in other browsers in your scenario. You can disable the supported control by using an script, getting the controls to apply it like $get("someClientID").getElementsByTagName("input");

Resources