2014年7月13日 星期日

[RESOLVED] Checkboxes in my gridview being unchecked don't remove value from Dictionary


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



Solved the problem with a combination of what I found there and a little of my own coding handywork. Primarily, the answer to my problem was found at

http://www.codeproject.com/Articles/202938/How-to-select-multiple-records-from-the-GridView-a


沒有留言:

張貼留言