<asp:GridView ID="GridView1" runat="server" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="id" HeaderText="用户ID" ReadOnly="True" />
<asp:BoundField DataField="name" HeaderText="用户姓名" />
<asp:BoundField DataField="sex" HeaderText="性别" />
<asp:BoundField DataField="nPlace" HeaderText="籍贯" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
SqlConnection sqlcon;
SqlCommand sqlcom;
string strCon = "Data Source=(local);Database=db_04;Uid=sa;Pwd=sa";
public void bind()
{
string sqlstr = "select * from tb_Member";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "tb_Member");
GridView1.DataSource = myds;
GridView1.DataKeyNames = new string[] { "id" };
GridView1.DataBind();
sqlcon.Close();
}
//编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
//删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sqlstr = "delete from tb_Member where id=‘" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "‘";
sqlcon = new SqlConnection(strCon);
sqlcom = new SqlCommand(sqlstr,sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
bind();
}
//更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
sqlcon = new SqlConnection(strCon);
string sqlstr = "update tb_Member set name=‘"
+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "‘,sex=‘"
+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "‘,nPlace=‘"
+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "‘ where id=‘"
+ GridView1.DataKeys[e.RowIndex].Value.ToString() + "‘";
sqlcom=new SqlCommand(sqlstr,sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
GridView1.EditIndex = -1;
bind();
}
//取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
GridVIew控件选中、编辑、取消、删除数据项