//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(); //正常绑定
}
}
/// <summary>
/// 主题:绑定数据,查询显示个人信息
/// 时间:2012年11月21日14:54:13
/// 描述:通过简单的方法绑定,实现数据显示
/// 作者:小伙
/// </summary>
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select top 5 * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
}
//实现分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.bind();
}
//删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sqlstr = "delete from person where pid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
con.Open();
cmd = new SqlCommand(sqlstr, con);
cmd.ExecuteNonQuery();
con.Close();
bind();
}
//取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
//编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
//更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlstr = "update person set pname='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',psex='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()+"',padress='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()+"',pyoubiao='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim()+"',pprice='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim()+"' where pid='"
+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
cmd = new SqlCommand(sqlstr, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}