| BoundField | HeaderText | DataField | ReadOnly |
| Employee ID | Employee ID | EmployeeID | true |
| First Name | First Name | FirstName | false |
| Last Name | Last Name | LastName | false |
图2:
protected void Page_Load(object sender, EventArgs e)
...{
if (!IsPostBack)
...{
BindGrid();
}
}
private void BindGrid()
...{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from employees", @"data source= .sqlexpress;initial catalog=northwind; integrated security=true");
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();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
...{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
...{
ViewState["sortexpression"] = e.SortExpression;
if (ViewState["sortdirection"] == null)
...{
ViewState["sortdirection"] = "asc";
}
else
...{
if (ViewState["sortdirection"].ToString() == "asc")
...{
ViewState["sortdirection"] = "desc";
}
else
...{
ViewState["sortdirection"] = "asc";
}
}
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();
}
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= .sqlexpress; initial catalog=northwind; integrated security=true");
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();
}
发表于 @ 2006年08月10日 13:06:00 | 评论( loading... ) | 举报| 收藏