功能为在GridView中可多选,全选/全不选各行,并提交处理
虽然在网上也查到其它方法,但我自己也写了一个,中间借用了他人的一些代码。
为突出重点,未列出完整代码,但相信大家能看明白,有问题的地方欢迎拍砖。
//在gridview中加入一模板列,放入checkbox,标题行中的checkAll可实现全选/全不选
<asp:TemplateField>
<ItemTemplate>
<input id="check" runat="server" type="checkbox" value='<%# Eval("newsid") %>' />
</ItemTemplate>
<HeaderTemplate>
<input id="checkAll" runat="server" type="checkbox" title="全选" onclick="javascript:checkAll
(this);" />
</HeaderTemplate>
<ItemStyle HorizontalAlign="center" CssClass="gv_cell" />
</asp:TemplateField>
//以下为javascript代码
<script type="text/javascript" language="javascript">
//若是选择当前行,则高亮显示,否则恢复原来的颜色
function highlightRow(theCheckBox, backColor, foreColor)
{
var theRow=theCheckBox.parentNode.parentNode;
if (theCheckBox.checked)
{
theRow.style.background='<%=highlightBackColor%>';
for (var i=0; i<theRow.childNodes.length; i++)
theRow.childNodes[i].style.color='<%=highlightForeColor%>';
}
else
{
theRow.style.background=backColor;
for (var i=0; i<theRow.childNodes.length; i++)
theRow.childNodes[i].style.color=foreColor;
}
}
function checkSelect()
{
elm=document.forms[0].elements;
for (i=0;i<elm.length;i++)
if (elm[i].type=="checkbox"&&elm[i].checked)
return true;
alert("请选择记录!");
return false;
}
function checkAll(theBox)
{
checkState=theBox.checked;
elm=theBox.form.elements;
for (i=0;i<elm.length;i++)
if (elm[i].type=="checkbox"&&elm[i].id!=theBox.id&&elm[i].checked!=checkState)
elm[i].click();
}
</script>
以上是aspx文件中代码,以下是aspx.cs
//使用checkbox选中行后,高亮显示的背景色和文字颜色常量
public const string highlightBackColor = "#666699";
public const string highlightForeColor = "#ffffff";
//用来将Color类型转为网页使用的颜色格式
string toWebColor(System.Drawing.Color theColor)
{
return "#"+Convert.ToString(theColor.R, 16) + Convert.ToString(theColor.G, 16) + Convert.ToString
(theColor.B, 16);
}
//动态添加checkbox客户端事件,并取得当前行颜色,作为参数加入
protected void gvNewsList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlInputCheckBox check = (HtmlInputCheckBox)e.Row.FindControl("check");
GridView gv = (GridView)sender;
string backColor,foreColor;
if (e.Row.RowState == DataControlRowState.Normal)
{
backColor = toWebColor(gv.RowStyle.BackColor);
foreColor = toWebColor(gv.RowStyle.ForeColor);
}
else if (e.Row.RowState == DataControlRowState.Alternate)
{
backColor = toWebColor(gv.AlternatingRowStyle.BackColor);
foreColor = toWebColor(gv.AlternatingRowStyle.ForeColor);
}
else
return;
check.Attributes.Add("onclick", "highlightRow(this,'" + backColor + "','" + foreColor + "')");
}
}
//收集选择行的ID,提交到相关处理方法,下面以删除为例
protected void buttonDelete_Click(object sender, EventArgs e)
{
string selectedID = "";
GridView gv = (GridView)((Button)sender).Parent;
for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.Rows[i];
HtmlInputCheckBox check = (HtmlInputCheckBox)row.FindControl("check");
if (check.Checked)
selectedID += check.Value + ",";
}
if (selectedID.Length > 0)
{
deleteRow(selectedID); //相关的删除方法
gvDataBind();
}
}