在gridview中添加选择框,并且头部的选择框可以实现全选
再添加一个删除按钮,可以删除所选中的行
步骤一:在gridview上添加一个模板列TemplateField,再对模板列进行编辑
步骤二:在源中加入javascript代码,实现头部HeaderTemplate的全选功能
<script type="text/javascript">
function SelectAll(tempControl)
{
var theBox=tempControl;
xState=theBox.checked;
elem=theBox.form.elements;
for(i=0;i<elem.length;i++)
{
if(elem[i].type=="checkbox" && elem[i].id!=theBox.id)
{
if(elem[i].checked!=xState)
{
elem[i].click();
}
}
}
}
步骤三:变现一段javascript实现改变选中行的颜色
function changecolor(cbo,o)
{
var theBox=cbo;
var tr=document.getElementById(o);
if(theBox.checked)
{
tr.style.backgroundColor="#ff33cc";
}
else
{
tr.style.backgroundColor="#ffffff";
}
}
</script>
再在.cs文件的DataBound中通过编写代码实现
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//
改变选中行的颜色
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckSingle = e.Row.Cells[9].FindControl("checkSingle") as CheckBox;
CheckSingle.Attributes.Add("onclick", "javascript:changecolor(this,'" + e.Row.ClientID + "')");
}
}
步骤四:点击删除按钮触发事件时的代码
protected void bt_delete_Click(object sender, EventArgs e)
{
int intCount = this.GridView1.Rows.Count;
for (int i = 0; i < intCount; i++)
{
CheckBox CheckSingle = this.GridView1.Rows[i].Cells[9].FindControl("checkSingle") as CheckBox;
if (CheckSingle.Checked)
{
int wybm = Convert.ToInt32(this.GridView1.Rows[i].Cells[2].Text);
int fjwybm = Convert.ToInt32(this.GridView1.Rows[i].Cells[3].Text);
string sql = "delete from AMS_SB_FJ where WYBM="+wybm+" and FJWYBM="+fjwybm;
SqlConnection sqlCon = DbCon.ReturnConn();
SqlCommand sqlCmd = new SqlCommand(sql,sqlCon);
sqlCmd.ExecuteNonQuery();
}
}
GridView1.DataBind();
}
在javascript中变量都是var型的,当为一个没有声明的变量赋值时javascript会自动为你声明一个var型的变量