protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Page.Title = "GridView使用";
this.BindToGridview();
}
}
//绑定方法
private void BindToGridview()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SqlConn"]);
SqlDataAdapter sda = new SqlDataAdapter("select * from test_gridView", conn);
DataSet ds = new DataSet();
sda.Fill(ds,"zyl");
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["sortexpression"]!=null)
{
dv.Sort=ViewState["sortexpression"].ToString()+" "+ViewState["sortdirection"].ToString();
}
this.GridView1.DataSource = dv;
this.GridView1.DataBind();
}
//分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
this.BindToGridview();
}
//排序
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";
}
}
this.BindToGridview();
}
//简单编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
this.BindToGridview();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
this.BindToGridview();
}
//更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id=this.GridView1.Rows[e.RowIndex].Cells[0].Text;
string sn=((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string login_date = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
Response.Write(id + sn + login_date);
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SqlConn"]);
conn.Open();
//SqlCommand cmd = new SqlCommand("update test_gridView set sn=@sn,login_date=@login_date where id=@id", conn);
//cmd.Parameters.Add(new SqlParameter("@sn", sn));
//cmd.Parameters.Add(new SqlParameter("@login_date", login_date));
//cmd.Parameters.Add(new SqlParameter("@id", id));
//cmd.ExecuteNonQuery();
string strSql = "update test_gridView set sn='" + sn + "',login_date='" + login_date + "' where id=" + id;
SqlCommand cmd= new SqlCommand(strSql, conn);
cmd.ExecuteNonQuery();
conn.Close();
this.GridView1.EditIndex = -1;
this.BindToGridview();
}
//鼠标移上变色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onMouseOver", "SetNewColor(this);");
e.Row.Attributes.Add("onMouseOut", "SetOldColor(this);");
}
}