【ADO.NET基础-GridView】GridView的编辑、更新、取消、删除以及相关基础操作代码

代码都是基础操作,后续功能还会更新,如有问题欢迎提出和提问.......

前台代码:

<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" AutoGenerateColumns="False" CellPadding="3" CellSpacing="1" GridLines="None" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanged="Page_Load" DataKeyNames="SID" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="8" OnRowDataBound="GridView1_RowDataBound"  >
             
               <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
              <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
               <PagerSettings Mode="NumericFirstLast" />
              <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
              <RowStyle BackColor="#DEDFDE" ForeColor="Black" />          
              <SortedAscendingCellStyle BackColor="#F1F1F1" />
              <SortedAscendingHeaderStyle BackColor="#594B9C" />
              <SortedDescendingCellStyle BackColor="#CAC9C9" />
              <SortedDescendingHeaderStyle BackColor="#33276A" />
              <Columns>
                   <asp:BoundField DataField="password" HeaderText="编号" ReadOnly="true" />
                   <asp:BoundField DataField="SID" HeaderText="学号" ReadOnly="true" />
                   <asp:BoundField DataField="name" HeaderText="姓名"  ControlStyle-Width="100"/>
                   <asp:BoundField DataField="sex" HeaderText="性别"  ControlStyle-Width="30"/>
                  <asp:BoundField DataField="age" HeaderText="年龄" ControlStyle-Width="30"/>
                   <asp:BoundField DataField="address" HeaderText="地址"  ControlStyle-Width="250"/>
                   <asp:BoundField DataField="phone" HeaderText="电话"  ControlStyle-Width="70"/>
                   <asp:BoundField DataField="qq" HeaderText="QQ" ControlStyle-Width="70"/>
                   <asp:BoundField DataField="time" HeaderText="注册时间"  HtmlEncode="false" DataFormatString="{0:yyyy-M-dd}" ReadOnly="true"/>
                 <asp:CommandField ButtonType="Button" HeaderText="操作" ShowDeleteButton="True" ShowEditButton="True"/>

              </Columns>
             
          </asp:GridView>

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ado.netDemo1
{
    public partial class Test1 : System.Web.UI.Page
    {
        SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString());
        protected void Page_Load(object sender, EventArgs e)
        {
            //string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString();
            //SqlConnection conn = new SqlConnection(connStr);
            //conn.Open();
            //string sql = "select * from tb_Students";
            //SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            //DataSet dataset = new DataSet();
            //adapter.Fill(dataset);
            //conn.Close();
            //GridView1.DataSource = dataset.Tables[0].ToString();
            //GridView1.DataBind();

            if(!IsPostBack)
            {
                shuaxin();
            }
            
        }

        //刷新数据
        private void shuaxin()

        {



            connStr.Open();
            string sql = "select * from tb_Students";
            SqlDataAdapter da = new SqlDataAdapter(sql, connStr);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)

            {

                GridView1.DataSource = ds;
              
                GridView1.DataBind();

            }
            GridView1.DataKeyNames = new string[] { "SID" };
            connStr.Close();

        }

        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            shuaxin();
        }
        //取消编辑
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            shuaxin();
        }
        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //( Name, Password, Sex, Age, Address, Phone, QQ)
            string sql = "update tb_Students set Name='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() +"',Sex='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "',Age='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim() + "',Address='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim() + "',Phone='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[6].Controls[0])).Text.ToString().Trim() + "',QQ='"
                +((TextBox)(GridView1.Rows[e.RowIndex].Cells[7].Controls[0])).Text.ToString().Trim() +"'where SID='"
                + GridView1.DataKeys[e.RowIndex].Value.ToString().Trim()+ "'";
            connStr.Open();
            SqlCommand cmd = new SqlCommand(sql,connStr);
            int EXQ = cmd.ExecuteNonQuery();
            if (EXQ == 1)
            {
                Response.Write("<script type=text/javascript>alert('更新成功!')</script>");
            }
            else
            {
                Response.Write("<script type=text/javascript>alert('更新失败!')</script>");
            }
            connStr.Close();
            GridView1.EditIndex = -1;
            shuaxin();


        }

        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
           
            string sql = "delete from tb_Students where SID='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
            connStr.Open();
            SqlCommand cmd = new SqlCommand(sql,connStr);
            int EXQ = cmd.ExecuteNonQuery();
            if (EXQ == 1)
            {
                Response.Write("<script type=text/javascript>alert('删除成功!')</script>");
            }
            else
            {
                Response.Write("<script type=text/javascript>alert('删除失败!')</script>");
            }
            connStr.Close();
            shuaxin();
            

        }
        //分页
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            shuaxin();
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();
        }
        //编号
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            //编号以及鼠标经过的背景更改
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ////鼠标经过时,行背景色变
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#95CACA'");
                ////鼠标移出时,行背景色变
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#F0F0F0'");

                ////当有编辑列时,避免出错,要加的RowState判断
                //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                //{
                // ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");
                //}

            }
            if (e.Row.RowIndex != -1)
            {
                int id = e.Row.RowIndex + 1;
                e.Row.Cells[0].Text = id.ToString();
            }

        }

    }
}

 

运行截图:

 

posted @ 2017-07-06 17:09  OldELeven  阅读(225)  评论(0编辑  收藏  举报