GridView 功能的实现

GridView 功能的实现

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="员工基本信息.aspx.cs" Inherits="WebApplication1.员工基本信息" EnableEventValidation="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
        GridView1 {
            margin: 10%;
        }

        body {
            background-color: #E7E7FF;
        }

        #TextBox1{
             width: 300px;
            box-sizing: border-box;
            border: 2px solid cornflowerblue;
            border-radius:8px;
            font-size: 16px;
            background-color:white;
            background-image: url('https://static.runoob.com/images/mix/searchicon.png');
            background-position: 10px 10px;
            background-repeat: no-repeat;
            padding: 12px 20px 12px 40px;
        }
       
        
     

        input[type=button], input[type=submit], input[type=reset] {
            background-color:cornflowerblue;
            border: none;
            border-radius:8px;
            color: white;
            padding: 8px 16px;
            text-decoration: none;
            margin: 4px 2px;
            cursor: pointer;
        }

       .view
       {
          width:100%; margin:0 auto;
       }

    </style>

</head>
<body>
    <form id="form1" runat="server">

        <div style="text-align: center">
            <br />
            <br />

            <asp:TextBox ID="TextBox1" runat="server" placeholder="搜索ID..." BorderStyle="Solid"></asp:TextBox>
            <br />
            <br />

           

            <asp:Button ID="Button1" runat="server" Text="搜索" OnClick="Button1_Click" />
            &nbsp;&nbsp;
            <asp:Button ID="Button2" runat="server" Text="重置" OnClick="Button2_Click" />

        </div>
        <br />




        <div class="view">                         
            <span style="color: rgb(51, 51, 51);  font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" style="text-align: center" AllowPaging="True" Font-Names="Arial" Font-Size="Medium" HorizontalAlign="Center" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" EnableModelValidation="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="ID" GridLines="None" Height="460px" Width="80%" EnablePersistedSelection="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting" >
                <AlternatingRowStyle BackColor="White" Font-Size="Medium" Width="300px" />
                
                <EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="80%" />
                <EmptyDataRowStyle Width="80%" />
                
                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <PagerSettings FirstPageText="" LastPageText="" NextPageText="" />
                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" Height="20px" Width="80%" />
                <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" Width="80%" />
                <SortedAscendingCellStyle BackColor="#FDF5AC" />
                <SortedAscendingHeaderStyle BackColor="#4D0000" />
                <SortedDescendingCellStyle BackColor="#FCF6C0" />
                
                <SortedDescendingHeaderStyle BackColor="#820000" />
                      
                


                 <Columns>
                   
                    <asp:TemplateField>
                       
                        <ItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </ItemTemplate>
                       
                    </asp:TemplateField>
                   
                    <asp:CommandField ButtonType="Image" CancelImageUrl="~/images/cancel.ico" DeleteImageUrl="~/images/delete.ico" EditImageUrl="~/images/edit.ico" ShowDeleteButton="True" ShowEditButton="True" UpdateImageUrl="~/images/refresh.ico" />
                </Columns>     
              





                 <PagerTemplate>
                  当前第:
                        
                 <asp:Label ID="LabelCurrentPage" runat="server" Text="<%# ((GridView)Container.NamingContainer).PageIndex + 1 %>"></asp:Label>/:
                                    
                 <asp:Label ID="LabelPageCount" runat="server" Text="<%# ((GridView)Container.NamingContainer).PageCount %>"></asp:Label><asp:LinkButton ID="LinkButtonFirstPage" runat="server" CommandArgument="First" CommandName="Page" Visible='<%#((GridView)Container.NamingContainer).PageIndex != 0 %>'>首页</asp:LinkButton>

                 <asp:LinkButton ID="LinkButtonPreviousPage" runat="server" CommandArgument="Prev" CommandName="Page" Visible='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>'>上一页</asp:LinkButton>
                                   
                 <asp:LinkButton ID="LinkButtonNextPage" runat="server" CommandArgument="Next" CommandName="Page" Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>下一页</asp:LinkButton>

                 <asp:LinkButton ID="LinkButtonLastPage" runat="server" CommandArgument="Last" CommandName="Page" Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>尾页</asp:LinkButton>

                   转到第
                 <asp:TextBox ID="txtNewPageIndex" runat="server" Width="20px" Text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' /><asp:LinkButton ID="btnGo" runat="server" CausesValidation="False" CommandArgument="-2" CommandName="Page" Text="GO" />


                </PagerTemplate>



            </asp:GridView>               
            </span>        
        </div>
    </form>
</body>
</html>

后台代码实现

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;

namespace WebApplication1
{

    public partial class 员工基本信息 : System.Web.UI.Page
    {
        private readonly string sql = "select * from 员工信息";
        private readonly string Constr = "server=.;initial catalog=公司人事管理系统;integrated security=true;";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                
                Show(sql);
            }

        }


        /*1、与数据库建立连接,执行sql,获取数据;
         
          2、用SqlDataAdapter和DataSet连用,用SqlDataAdapter来获得数据库中的数据,填充至DataSet中。

         首先,为了从SQL数据库执行select查询,通过连接字符串建立一个连接到数据库的SqlConnection对象,
         然后构造一个包含查询语句的SqlDataAdapter对象。为了用查询的返回结果填充到DataSet 对象,
         需要调用SqlDataAdapter的Fill方法。
 */
        //展示
        private void Show(string sql)                              //定义方法显示
        {

            SqlConnection conn = new SqlConnection(Constr);        //创建数据库连接实例
            try
            {
                conn.Open();                                       //打开数据库连接
                DataSet ds = new DataSet();                        //声明并初始化
                SqlDataAdapter da = new SqlDataAdapter(sql, conn); //与数据库建立连接,执行sql,获取数据;
                da.Fill(ds, "message");                            //填充到ds,message表中
                GridView1.DataSource = ds.Tables["message"];       //获得数据源
                GridView1.DataBind();                              //绑定到GridView1控件
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());                 //显示出错信息
            }
            finally
            {
                conn.Close();                                       //关闭数据库连接
            }

        }

        //搜索
        protected void Search()
        {
            if (TextBox1.Text.ToString().Trim() != null)
            {
                string id = TextBox1.Text.ToString().Trim();
                string sql = "select * from 员工信息 where ID like '%" + id + "%';";
                Show(sql);

            }
            else
            {
                Response.Write(@"<script>alert('请输入内容!');</script>");
            }
        }

        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SqlConnection conn = new SqlConnection(Constr);
            try
            {
                DialogResult dr = MessageBox.Show("是否删除", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dr == DialogResult.Yes)
                {

                    string s = "delete from 员工信息 where ID='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
                    SqlCommand cmd = new SqlCommand(s, conn);
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    if (i > 0)
                    {
                        Response.Write(@"<script>alert('删除成功!');</script>");
                    }
                    else
                    {
                        Response.Write(@"<script>alert('删除失败!');</script>");
                    }

                }

            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                Show(sql);
                conn.Close();
            }

        }

        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            Show(sql);
        }

        //取消
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            string sql = "select * from 员工信息";
            Show(sql);
        }

        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            SqlConnection conn = new SqlConnection(Constr);
            try
            {
                string ID = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
                int rowNum = e.RowIndex;

                string 姓名 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[3].Controls[0])).Text.ToString().Trim();
                string 性别 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[4].Controls[0])).Text.ToString().Trim();              
                string 籍贯 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[5].Controls[0])).Text.ToString().Trim();
                string 民族 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[6].Controls[0])).Text.ToString().Trim();
                string 联系电话 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[7].Controls[0])).Text.ToString().Trim();
                string 职位 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[8].Controls[0])).Text.ToString().Trim();
                string 家庭住址 = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[rowNum].Cells[9].Controls[0])).Text.ToString().Trim();

                
                string s = "update 员工信息 set 姓名='" + 姓名 + "',性别='" + 性别 + "',籍贯='" + 籍贯 + "', " +"民族='" + 民族 + "',联系电话='" + 联系电话 + "',职位='" + 职位 + "',家庭住址='" + 家庭住址 + "' where ID='" + ID + "'";
                Console.WriteLine(姓名);
                
                SqlCommand cmd = new SqlCommand(s, conn);
            conn.Open();
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Response.Write(@"<script>alert('更新成功!');</script>");
            }
            else
            {
                Response.Write(@"<script>alert('更新失败!');</script>");
            }
            
                
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                
                conn.Close();
                GridView1.EditIndex = -1;
                Show(sql);

            }
        }

        //分页
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            // 得到该控件
            GridView theGrid = sender as GridView;
            int newPageIndex = 0;
            if (e.NewPageIndex == -3)
            {
                //点击了Go按钮
                System.Web.UI.WebControls.TextBox txtNewPageIndex = null;

                //GridView较DataGrid提供了更多的API,获取分页块可以使用BottomPagerRow 或者TopPagerRow,当然还增加了HeaderRow和FooterRow
                GridViewRow pagerRow = theGrid.BottomPagerRow;

                if (pagerRow != null)
                {
                    //得到text控件
                    txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as System.Web.UI.WebControls.TextBox;
                }
                if (txtNewPageIndex != null)
                {
                    //得到索引
                    newPageIndex = int.Parse(txtNewPageIndex.Text) - 1;
                }
            }
            else
            {
                //点击了其他的按钮
                newPageIndex = e.NewPageIndex;
            }
            //防止新索引溢出
            newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
            newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;

            //得到新的值
            theGrid.PageIndex = newPageIndex;

            //重新绑定
            Show(sql);

        }

        //排序
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            
            Show(sql);
        }

        //按钮功能实现
        protected void Button1_Click(object sender, EventArgs e)
        {
            Search();
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            string sql = "select * from 员工信息";
            Show(sql);
        }


    
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值