.NET2.0下一个标准GRIDVIEW功能的实现
最后,实现编辑功能,因为在aspx页面中已经设置了OnRowEditing="GridView1_RowEditing",其中GridView1_RowEditing的代码为
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
...{
int empid;
string fname, lname;
empid = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
fname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
lname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
![]()
SqlConnection cnn = new SqlConnection(@"data source=localhost;initial catalog=northwind;user id=sa;password=123456");
cnn.Open();
SqlCommand cmd = new SqlCommand("update employees set firstname=@fname,lastname=@lname where employeeid=@empid", cnn);
cmd.Parameters.Add(new SqlParameter("@fname",fname));
cmd.Parameters.Add(new SqlParameter("@lname", lname));
cmd.Parameters.Add(new SqlParameter("@empid", empid));
cmd.ExecuteNonQuery();
cnn.Close();
![]()
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
...{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
...{
GridView1.EditIndex = -1;
BindGrid();
}
可以看到,上面的代码和asp.net 1.1版本的其实原理是差不多的。最后,bindgrid()的过程很简单:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from employees", @"data source=localhost;initial catalog=northwind;user id=sa;password=123456");
da.Fill(ds,"employees");
DataView dv = ds.Tables[0].DefaultView;
![]()
if (ViewState["sortexpression"] != null)
...{
dv.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString();
}
![]()
GridView1.DataSource=dv;
GridView1.DataBind();
这里gridview绑定的是dataview,并且用dv.sort设定了每次排序的顺序,也就是说,每次排序后其顺序都是保持不变的。当然最后是page_load事件
protected void Page_Load(object sender, EventArgs e)
...{
if(!IsPostBack)
...{
BindGrid();
}
}
0
相关文章
