前一段时间做一个项目,用户要在Gridview中选择数据,然后进行操作,考虑半天,觉得还是用CheckBox比较简单,就在GridView中增加了一个模板列,添加CheckBox控件,然后添加全选的CheckBox,然后添加一个取消的按钮,还有一个确定的按钮进行数据库的操作,前端的设计大致如下。
那就把代码贴出来吧:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class UpdatePeopleStatus : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["strcon"]);//创建数据库连接
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()//显示查询结果
{
DataTable myTable = new DataTable();
myTable = DbOperation.GetPeople(TxtName.Text.ToString().Trim());
GridView1.DataSource = myTable;
GridView1.DataBind();
}
protected void BtnQueryPeople_Click(object sender, EventArgs e)//查询所有用户
{
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)//分页显示
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)//注意这里要添加CheckBox的Autopostback的属性
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox2.Checked == true)
{
cbox.Checked = true;
}
else
{
cbox.Checked = false;
}
}
}
protected void BtnCancel_Click(object sender, EventArgs e)
{
CheckBox2.Checked = false;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cbox.Checked = false;
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked==true)
{
string strsql = "Update People set 加班补助=1 where 卡号='" + GridView1.Rows[i].Cells[1].Text + "'";
SqlCommand comm = new SqlCommand(strsql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
BindData();
Response.Write("<script>alert('修改加班补助成功');</script>");
Response.Write("<script language='javascript'>window.location.href=window.location.href;</script>");//重定向页面
}
protected void BtnReset_Click(object sender, EventArgs e)
{
DbOperation.UpdatePeople();
Response.Write("<script>alert('重置补助成功!');</script>");
Response.Write("<script language='javascript'>window.location.href=window.location.href;</script>");//重定向页面
}
}