GridView跨页多选
JS 前台:
//GridView中实现多选效果
function CheckAllC(oCheckbox) {
var GridView1 = document.getElementById('gvDataList');
for (i = 1; i < gvDataList.rows.length; i++) {
GridView1.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = oCheckbox.checked;
}
}
后台:
1:GridView翻页PageIndexChanging事件中调用获取多选主键信息,还需要判断一下,翻页之前是否已经有数据选中。具体方法如下:
方法如下:
#region 存储GridView翻页数据主键
/// <summary>
/// 存储GridView翻页数据主键
/// </summary>
private void RememberOldValues()
{
Dictionary<string, string> list = Session["SelectedObject"] as Dictionary<string, string>;
if (list == null)
{
list = new Dictionary<string, string>();
}
foreach (GridViewRow row in gvDataList.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSelect");
string user = gvDataList.DataKeys[row.RowIndex].Value.ToString();
if (Session["SelectedObject"] != null)
list = (Dictionary<string, string>)Session["SelectedObject"]; //很重要
if (cb.Checked)
{
if (!list.ContainsKey(user))
{
list.Add(user, "null");
}
}
else
{
if (list.ContainsKey(user))
{
list.Remove(user);
}
}
if (list != null && list.Count > 0)
Session["SelectedObject"] = list;
}
}
#endregion
附带GridView自带分页:
#region 分页
protected void gvDataList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
// 得到该控件
GridView theGrid = sender as GridView;
int newPageIndex = 0;
if (e.NewPageIndex == -3)
{
//点击了Go按钮
TextBox txtNewPageIndex = null;
//GridView较DataGrid提供了更多的API,获取分页块可以使用BottomPagerRow 或者TopPagerRow,当然还增加了HeaderRow和FooterRow
GridViewRow pagerRow = theGrid.BottomPagerRow;
if (pagerRow != null)
{
//得到text控件
txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;
}
if (txtNewPageIndex != null)
{
//得到索引
newPageIndex = int.Parse(txtNewPageIndex.Text) - 1;
}
}
else
{
//点击了其他的按钮
newPageIndex = e.NewPageIndex;
}
//防止新索引溢出
newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;
//得到新的值
theGrid.PageIndex = newPageIndex;
//重新绑定
BindItems(0, NodeID, strSearch);
}
#endregion
2:点击提交按钮时,需要获取下GridView中的多选主键ID
#region 获取单选按钮选中的主键ID
/// <summary>
/// 获取单选按钮选中的主键ID
/// </summary>
/// <returns></returns>
private void GetPkID()
{
Dictionary<string, string> list = Session["SelectedObject"] as Dictionary<string, string>;
if (list == null)
{
list = new Dictionary<string, string>();
}
foreach (GridViewRow row in gvDataList.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSelect");
string user = gvDataList.DataKeys[row.RowIndex].Value.ToString();
if (cb.Checked)
{
if (!list.ContainsKey(user))
{
list.Add(user, "null");
}
}
else
{
if (list.ContainsKey(user))
{
list.Remove(user);
}
}
}
ViewState["SelectedObject"] = list;
}
#endregion