gridview自定义编辑和删除
1、页面上拖动数据源控件sqldatasource1,设置数据源
2、页面上拖出一gridview1控件,注意不能绑定数据源,设置如下属性:
3、找到gridview1的属性窗口,单击事件按钮后,(如图,第4个)。在下面的事件中,找到GridView1_RowCancelingEdit,在后面的空白处单击,系统自动生成该事件首部,自行在内部编写代码。其它事件还有:GridView1_RowDeleting、GridView1_RowUpdating、GridView1_RowEditing,一共4个。
4、编写grivview1的数据绑定函数gw_bind():
protected void gw_bind()
{
SqlConnection mycn=new SqlConnection ("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\wy\\stu10.mdf;Integrated Security=True;User Instance=True");
string mystr="select 学号,姓名,性别,班级 from student";
SqlCommand mycm=new SqlCommand (mystr,mycn);
SqlDataAdapter myda=new SqlDataAdapter (mycm);
DataSet ds=new DataSet ();
myda.Fill(ds,"qqq");
GridView1.DataSource=ds.Tables[0];
GridView1.DataKeyNames = new string[] { "学号" }; // 很重要的语句,必须设置主键,否则出错!
GridView1.DataBind();
}
5、页面首次加载时,执行绑定!
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
gw_bind();
}
6、单击“编辑”按钮时执行的代码
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gw_bind();
}
7、单击“更新”按钮时执行的代码
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection mycn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\wy\\stu10.mdf;Integrated Security=True;User Instance=True");
string xh = GridView1.DataKeys[e.RowIndex].Value.ToString();
string xm = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.Trim();
string xb = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.Trim();
string bj = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.Trim();
string mystr = "update student set 姓名='"+xm+"',性别='"+xb+"',班级='"+bj+"' where 学号="+xh;
SqlCommand mycm = new SqlCommand(mystr, mycn);
mycn.Open();
mycm.ExecuteNonQuery();
GridView1.EditIndex = -1;
gw_bind();
}
8、单击“删除”按钮时执行的代码
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection mycn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\wy\\stu10.mdf;Integrated Security=True;User Instance=True");
string xh = GridView1.DataKeys[e.RowIndex].Value.ToString();
string mystr = "delete student where 学号=" + xh;
SqlCommand mycm = new SqlCommand(mystr, mycn);
mycn.Open();
mycm.ExecuteNonQuery();
GridView1.EditIndex = -1;
gw_bind();
}
9、单击“取消”按钮时执行的代码
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gw_bind();
}
说明:数据源的设置是为了方便拿到连接字符串,数据库源文件stu10.rar已上传至本网站文件管理中!