<asp:GridView ID="gvYwAssign" runat="server" AutoGenerateColumns="False"
AllowPaging="True" OnPageIndexChanging="gvYwAssign_PageIndexChanging"
DataSourceID="ObjectDs" OnRowDataBound="gvYwAssign_RowDataBound" PageSize="5">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ckbSelAll" runat="server" Text="全选" OnCheckedChanged="cbSelAll_CheckedChanged" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="ckbxSel" runat="server" ToolTip='<%#Eval("id") %>' OnCheckedChanged="ckbxSel_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
--代码页
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2JinE : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] strallItems = new string[] { };
ViewState["allItems"] = strallItems;
}
}
//单个选中与取消
protected void ckbxSel_CheckedChanged(object sender, EventArgs e)
{
string[] strSelectFen = (string[])ViewState["allItems"];
List<string> listSelect = strSelectFen.ToList();
CheckBox chk = (CheckBox)sender;
DataControlFieldCell dcf = (DataControlFieldCell)chk.Parent; //这个对象的父类为cell
GridViewRow gr = (GridViewRow)dcf.Parent; //cell的父类就是row,这样就得到了该checkbox所在的该行
string nowId = chk.ToolTip;
if (true == chk.Checked)
{
if (false == listSelect.Contains(nowId))
{
listSelect.Add(nowId);
}
}
else
{
if (true == listSelect.Contains(nowId))
{
listSelect.Remove(nowId);
}
}
strSelectFen = listSelect.ToArray();
ViewState["allItems"] = strSelectFen;
}
//全选与取消
protected void cbSelAll_CheckedChanged(object sender, EventArgs e)
{
string[] strSelectFen = (string[])ViewState["allItems"];
List<string> listSelect = strSelectFen.ToList();
string nowId;
CheckBox cb1 = gvYwAssign.HeaderRow.FindControl("ckbSelAll") as CheckBox;
if (cb1.Checked)//选中
{
for (int i = 0; i < gvYwAssign.Rows.Count; i++)
{
CheckBox cb2 = gvYwAssign.Rows[i].FindControl("ckbxSel") as CheckBox;
cb2.Checked = true;
nowId = cb2.ToolTip;
if (false == listSelect.Contains(nowId))
{
listSelect.Add(nowId);
}
}
}
else//取消
{
for (int i = 0; i < gvYwAssign.Rows.Count; i++)
{
CheckBox cb2 = gvYwAssign.Rows[i].FindControl("ckbxSel") as CheckBox;
cb2.Checked = false;
nowId = cb2.ToolTip;
listSelect.Remove(nowId);
}
}
strSelectFen = listSelect.ToArray();
ViewState["allItems"] = strSelectFen;
}
//包括绑定原来选项
protected void gvYwAssign_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//绑定原来选项
string[] strSelectFen = (string[])ViewState["allItems"];
CheckBox chk = e.Row.FindControl("ckbxSel") as CheckBox;
string nowId = chk.ToolTip;
for (int j = 0; j < strSelectFen.Length; j++)
{
if (nowId == strSelectFen[j])
{
chk.Checked = true;
}
}
}
}
}