locked
Checkboxes in my gridview being unchecked don't remove value from Dictionary RRS feed

  • Question

  • User-718146471 posted

    We just uncovered an odd bug in this gridview with checkboxes. (original thread: http://forums.asp.net/post/4691898.aspx) The idea is to store the checkboxes that are checked into a dictionary that has (username, boolean) in this case the key is username, the value is boolean. As I step through the checkbox state, I'm wanting to make it so when someone unchecks a username checkbox, it gets stripped from the checkbox dictionary. It doesn't seem to be working. I'm using the viewstate to try to keep track of which checkboxes are checked. I guess this is what I get for trying to use GridView with paging, ugh! Here's the code:

     

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblName = ((Label)e.Row.FindControl("lblName"));
                DataRowView _dv = (DataRowView)e.Row.DataItem;
                UserInformation _u = new UserInformation((string)_dv.Row["USER"], false);
                if (_u.Name != null)
                {
                    lblName.Text = _u.Name;
                    _u = null;
                }
                else
                {
                    e.Row.Visible = false;
                }
                String id = (String)GridView1.DataKeys[e.Row.RowIndex].Value;
                if (!_checkBoxDictionary.ContainsKey(id))
                {
                    _checkBoxDictionary.Add(id, false);
                }
                CheckBox checkBox = (CheckBox)e.Row.FindControl("chkSelect");
                checkBox.Checked = _checkBoxDictionary[id];
            }
        }
    
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            _checkBoxDictionary = (Dictionary<String, Boolean>)ViewState["CheckBoxDictionary"];
        }        
    
        protected override object SaveViewState()
        {
            ViewState["CheckBoxDictionary"] = _checkBoxDictionary;
            return base.SaveViewState();
        }
    
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                String id = (String)GridView1.DataKeys[row.RowIndex].Value;
                CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
                _checkBoxDictionary[id] = checkBox.Checked;
            }
        }
    
    

    Tuesday, July 2, 2013 2:36 PM

Answers

All replies