/*自定义导航栏*/

【ASP】GridView相关事件操作

描述:对GridView分页,选择,增删改查等操作

   

绑定GridView,并且显示数据
        public void BindGridView()
        {
            SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true");
            SqlDataAdapter da = new SqlDataAdapter("select *from stuInfo",con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.Caption = "学生信息表";                                    //显示表头
            GridView1.DataKeyNames = new String[] {"sno"};                //定义主键
            GridView1.DataBind();
        }
显示详细信息
        protected void GridView1_SelectedIndexChanging1(object sender, GridViewSelectEventArgs e)
        {
            string no = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
            SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true");
            SqlDataAdapter da = new SqlDataAdapter("select *from stuInfo where sno='" + no + "'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView2.DataSource = ds;
            GridView2.Caption = "学生详细信息表";
            GridView2.DataBind();
        }
实现分页功能
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGridView();
        }
实现编辑功能
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.BindGridView();
        }
实现取消编辑功能
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            this.BindGridView();
        }
实现更新数据功能
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                string no = GridView1.DataKeys[e.RowIndex].Value.ToString();
                string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
                SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true");
                con.Open();
                SqlCommand cmd = new SqlCommand("update stuInfo set sname='" + name + "' where sno='" + no + "'",con);
                cmd.ExecuteNonQuery();
                con.Close();

 

                GridView1.EditIndex = -1;
                this.BindGridView();
            }
            catch (Exception e1)
            {
                Response.Write(e1);
            }
        }
    }
}

 

posted @ 2012-11-14 11:53  伏草惟存  阅读(344)  评论(0编辑  收藏  举报