Nitin Vijay
Nitin Vijay

Reputation: 1422

CheckBox Check is not Working on server side in Gridview

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;
            }

Upvotes: 0

Views: 2607

Answers (2)

erichste
erichste

Reputation: 759

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.
     }
}

Upvotes: 0

Adil
Adil

Reputation: 148180

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.

Upvotes: 1

Related Questions