Gridview的基本用法

来源:互联网 发布:淘宝登陆页面无法显示 编辑:程序博客网 时间:2024/05/16 19:04

Gridview 基本用法--aspnetpage

(1)引用AspNetPager.dll 文件

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default9.aspx.cs" Inherits="Default9" %>

<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
    <style type="text/css">
      div{
         font-size:15px;
      }
   
    </style>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" DataKeyNames="id,number">
            <RowStyle BackColor="#EFF3FB" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <Columns>
                <asp:BoundField DataField="id" HeaderText="编号" />
                <asp:BoundField DataField="number" HeaderText="数字" />
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
                <asp:CommandField ShowSelectButton="True" />
            </Columns>


        </asp:GridView>

           <table cellpadding="0" cellspacing="0" align="center" width="99%" class="border">
            <tr>
              <td align="left" colspan="2" style="height: 18px">
                 <Webdiyer:AspNetPager id="AspNetPager2" runat="server" HorizontalAlign="Right"  FirstPageText="<<" LastPageText=">>" PrevPageText="<" NextPageText=">" NumericButtonTextFormatString="-{0}-" Width="600px"
                  ShowCustomInfoSection="Left" ShowBoxThreshold="2" PageSize="5"  InputBoxClass="text2" TextAfterInputBox="" OnPageChanging="AspNetPager1_PageChanging"  />
                 </td>
             </tr>
            </table>
           <br />

    </form>
</body>
</html>

.cs 文件

--------------------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/*
 * 作者:靳志远 (jack15850798154)
 * 时间:2010-04-02
 * 说明:Gridview 的基本用法;
 */
public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Gridview数据绑定;
           // databind();


            //aspnetpager的基本用法;
            SqlConnection con = new SqlConnection("server=.;DataBase=master;user=sa;pwd=sql; ");
            con.Open();
            SqlCommand cmd = new SqlCommand("select  count(*) from a", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
             AspNetPager2.AlwaysShow = true;
            AspNetPager2.PageSize = 2;
            AspNetPager2.RecordCount = (int)cmd.ExecuteScalar();
            con.Close();
            databind();
        }
    }
    /// <summary>
    /// 绑定数据
    /// </summary>
    public void databind()
    {
        SqlConnection con = new SqlConnection("server=.;DataBase=master;user=sa;pwd=sql; ");
        con.Open();
        SqlCommand cmd = new SqlCommand("select  * from a", con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        con.Close();
    }
    /// <summary>
    /// Gridview1_PageIndexChanging
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

        GridView1.PageIndex = e.NewPageIndex;
        SqlConnection con = new SqlConnection("Data Source=.;DataBase=master;uid=sa;pwd=sql; ");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from a", con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();


        con.Close();
    }
    /// <summary>
    /// 当鼠标经过GridView的行的时候变色。离开不变色
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           //鼠标经过时,行背景色变
            e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#E6F5FA'");
            //鼠标移出时,行背景色变
            e.Row.Attributes.Add("onmouseout","this.style.backgroundColor='#FFFFFF'");
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //this.Label1.Text = this.TextBox1.Text.Trim();
        //this.Button1.Text = this.TextBox1.Text.Trim();
        //this.DropDownList1.Items.Add("啊啊啊啊");
        //this.DropDownList1.Items.Add("bb");
        //this.DropDownList1.Items.Add("ccccccc");
        //this.DropDownList1.Items.Add("ddddd");

    //  <!--  <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><!--服务器端控件占用服务器段内存的-->
    //   <!-- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   //     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />-->
   // <!--    <asp:DropDownList ID="DropDownList1" runat="server">
   //     </asp:DropDownList>
   // 用户名:      <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>-->
   //     <!--ControlToValidate  为必填写,ErrorMessage 为错误信息-->
   //  <!-- <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2"
      //      ErrorMessage="*"></asp:RequiredFieldValidator></div>-->
 
    }
    /// <summary>
    /// GridView1的行编辑事件;
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;
        databind();
    }


    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {

    }

    /// <summary>
    /// GridView1的行删除事件;
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex][0].ToString());
     
        int i = deletesql(id);
        if (i > 0)
        {
            Response.Write("<script>alert('删除成功')</script>");
        }
        else
        {
            Response.Write("<script>alert('删除失败')</script>");
        }
        databind();

    }
    /// <summary>
    /// GridView1的行修改事件;
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
      int id=Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex][0].ToString());
       string name= ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
     int i=  updatesql(id, name);
     if (i > 0)
     {
         Response.Write("<script>alert('修改成功')</script>");
     }
     else
     {
         Response.Write("<script>alert('修改失败')</script>");
     }
    }
    /// <summary>
    /// 修改SQL根据ID 来修改number;
    /// </summary>
    /// <param name="id"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public int updatesql(int id, string number)
    {
        SqlConnection con = new SqlConnection("Data Source=.;DataBase=master;uid=sa;pwd=sql;");
        con.Open();
        SqlCommand cmd = new SqlCommand("update a set number=@number where id=@id",con);
        cmd.Parameters.Add("@number",number);

        cmd.Parameters.Add("@id",id);
        int i = cmd.ExecuteNonQuery();
        con.Close();
        return i;
     
    }
    /// <summary>
    /// 删除SQL根据ID;
    /// </summary>
    /// <param name="id"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public int deletesql(int id)
    {
        SqlConnection con = new SqlConnection("Data Source=.;DataBase=master;uid=sa;pwd=sql;");
        con.Open();
        SqlCommand cmd = new SqlCommand("delete a  where id=@id", con);
         cmd.Parameters.Add("@id", id);
        int i = cmd.ExecuteNonQuery();
        con.Close();
        return i;

    }

    /// <summary>
    /// 编辑中取消事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.GridView1.EditIndex = -1;
        databind();
    }


    /// <summary>
    /// aspnetpager的pagechanging;
    /// </summary>
    /// <param name="src"></param>
    /// <param name="e"></param>
    protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        this.AspNetPager2.CurrentPageIndex = e.NewPageIndex;
        SqlConnection con = new SqlConnection("Data Source=.;DataBase=master;uid=sa;pwd=sql; ");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from a", con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet dt = new DataSet();

        adapter.Fill(dt, AspNetPager2.PageSize * (AspNetPager2.CurrentPageIndex - 1), AspNetPager2.PageSize, "a");
        GridView1.DataSource = dt.Tables["a"];
        GridView1.DataBind();
        con.Close();
    }
}

原创粉丝点击