Gridview控件

来源:互联网 发布:2017淘宝客综合权重 编辑:程序博客网 时间:2024/05/01 00:24

一、GridView和DataGrid的异同

GridView 是 DataGrid的后继控件,在.net framework 2 中,虽然还存在DataGrid,但是GridView已经走上了历史的前台,取代DataGrid的趋势已是势不可挡。GridView和DataGrid功能相似,都是在web页面中显示数据源中的数据,将数据源中的一行数据,也就是一条记录,显示为在web页面上输出表格中的一行。

GridView相对于DataGrid来说,具有如下优势,功能上更加丰富,因为提供了智能标记面板(也就是show smart tag)更加易用方便,常用的排序、分页、更新、删除等操作可以零代码实现!具有PagerTemplate属性,可以自定义用户导航页面,也就是说分页的控制更加随心所欲。GridView和DataGrid在事件模型上也多有不同之处,DataGrid控件引发的都是单个事件,而GridView控件会引发两个事件,一个在操作前发生,一个在操作后发生,操作前的事件多位***ing事件,操作后的事件多位***ed事件,比如Sorting 事件和sorted 事件,RowDeleting和RowDeleted事件。

二、GridView数据操作

1.显示数据:

这个比较简单就不废话了。

2.分页

GridView把数据显示出来了,但是那么多条记录罗列到一页上是不合适的,我们应该对数据进行分页。还记得在asp时代,分页是多么的麻烦,需要编写很多的代码,而且各种分页组件也应运而生。而在GridView中,您会发现,分页是如此的简单,只需要您轻点鼠标,在Show Smart Tag中,选中Enable Paging,表格的分页操作变完成了,是不是So Easy呢。

并不是什么数据源都可以让GridView实现自动分页的,比如如果DataSourceMode是DataReader,就无法实现自动分页。而且只有ObjectDataSource是界面级别的支持分页,类似我们常用的SqlDataSource都是先提取所有的记录,然后只显示本页需要显示的记录,然后抛弃其余的记录,都有点浪费资源的啦!

当GridView的AllowPaging属性设置为True的时候,我们实现了分页,我们还可以对分页进行一些个性化的设置。常用的属性包括:PageIndex——设置数据显示的当前页面,默认是0,也就是数据的首页。PageSize ——也就是一页显示多少条记录,默认为10条。在PagerSettings中,还可以对分页的导航按钮进行详细设置,在Mode属性中,可以设置:Numeric——默认的,分页用数字表示,1,2,3……。NextPrevious、NextPreviousFirstLast、NumericFirstLast均可顾名思义,显示上一页、下一页、首页、末页等。当Mode设定不是Numeric时,那么可以通过设定FirstPageText、LastPageText等属性来实现分页导航时,到首页、末页、下页、上页时显示的文字提示。

如果想实现分页界面的完全自动控制,还可以点击GridView右键,选择编辑模版-PagerTemplate来实现,在模版中加入若干个Button控件,然后将Button控件的CommandName属性设置为Page,将CommandArgument属性分别设置为First、Last、Prev、Next或者一个数字,即可实现分页操作。
示例代码:(绑定数据库方法:BindData())

绑定数据源
//进行分页时必须绑定这个事件 
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if ((GridView1.PageIndex >= 0) && (GridView1.PageIndex < GridView1.PageCount))
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindData();
        }
       
    }
//跳转到TextBox1中数值的页面
    protected void Button1_Click(object sender, EventArgs e)
    {
        int i = int.Parse(TextBox1.Text);
        if ((i >= 0) && (i < GridView1.PageCount))
        {
            GridView1.PageIndex = i-1;
            BindData();
        }
        if (i < 0)
        {
            GridView1.PageIndex = 0;
            BindData();
        }
        if (i > GridView1.PageCount)
        {
            GridView1.PageIndex = GridView1.PageCount;
            BindData();
        }
    }
//首页
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex > 0)
        {
            GridView1.PageIndex = 0;
            BindData();
        }
        else
        {
                 }
    }
//末页
    protected void Button5_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex <GridView1.PageCount)
        {
            GridView1.PageIndex = GridView1.PageCount;
            BindData();
        }
        else
        {
                  }
    }
//上一页
    protected void Button3_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex > 0)
        {
            GridView1.PageIndex = GridView1.PageIndex - 1;
            BindData();
        }
        else
        {
                   }
    }
//下一页
    protected void Button4_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex < GridView1.PageCount)
        {
            GridView1.PageIndex = GridView1.PageIndex + 1;
            BindData();
        }
        else
        {
                   }
    }
3.自定义某一行的颜色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        //首先检查,当前的行是否属于datarow类型的行,
        //因为象gridview中的headerrow,footerrow等行,并不包含实际的数据,因此,
        //我们不需要使用headerrow和footerrow
        {
            string id = DataBinder.Eval(e.Row.DataItem, "CustomerID").ToString();//获取字段CustomerID
            if (id == "ALFKI")//判断CustomerID是否为ALFKI,如果是则修改该行的背景色为Red
            {
                e.Row.BackColor = Color.Red;
            }
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='blue'");//鼠标移入显示的颜色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");//鼠标移出显示的颜色
}
4.鼠标移到GridView上显示当前行的值,起到Tip的作用
  • 1.   定义<div>的样式:

<style type="text/css">

.transparent { FILTER: alpha(opacity=85);

BORDER-TOP: indianred 1px solid;


BORDER-RIGHT: indianred 1px solid; 

BORDER-LEFT: indianred 1px solid;

BORDER-BOTTOM: indianred 1px solid;

POSITION: absolute;

BACKGROUND-COLOR: infobackground;

DISPLAY: none  }
</style>

  • 2、显示和隐藏窗体的脚本:

<script language="javascript">
     //显示弹出窗体
     function Show(Country, City, Address, PostalCode, Phone, Fax)
     {

         document.getElementById("td1").innerText="国家:"+Country;

         document.getElementById("td2").innerText="城市:"+City;

         document.getElementById("td3").innerText="地址:"+Address;

         document.getElementById("td4").innerText="邮政编码:"+PostalCode;

         document.getElementById("td5").innerText="电话:"+Phone;

         document.getElementById("td6").innerText="传真:"+Fax;

         //获得鼠标的X轴的坐标
         x = event.clientX + document.body.scrollLeft;
         //获得鼠标的Y轴的坐标
         y = event.clientY + document.body.scrollTop + 20;
         //显示弹出窗体
         Popup.style.display="block";
         //设置窗体的X,Y轴的坐标
         Popup.style.left = x;
         Popup.style.top = y;
     }

//隐藏弹出窗体
function Hide()
     {

         //隐藏窗体
         Popup.style.display="none";
    }

</script>

 3、ToolTip窗体的代码
<div id="Popup" class="transparent" style=" Z-INDEX: 200">
     <table border="0" cellpadding="0" style="FONT-SIZE: x-small">
          <tr>
<td align="middle" bgcolor="indianred"><font color="white">联系方式</font></td>
</tr>
         <tr><td id="td1"></td></tr>
         <tr><td id="td2"></td></tr>
         <tr><td id="td3"></td></tr>
         <tr><td id="td4"></td></tr>
         <tr><td id="td5"></td></tr>
        <tr><td id="td6"></td></tr>
     </table>
</div>

  • 4.后台代码处理

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
               e.Row.Attributes.Add("onmouseover",
"this.oldcolor=this.style.backgroundColor;this.style.backgroundColor='#C8F7FF';");
            e.Row.Attributes.Add("onmousemove",
   "Show('" + e.Row.Cells[3].Text.ToString() + "','"
                          + e.Row.Cells[4].Text.ToString() + "','"
                          + e.Row.Cells[5].Text.ToString() + "','"
                          + e.Row.Cells[6].Text.ToString() + "','"
                          + e.Row.Cells[7].Text.ToString() + "','"
                          + e.Row.Cells[8].Text.ToString() + "');");


            e.Row.Attributes.Add("onmouseout",
    "this.style.backgroundColor=this.oldcolor;Hide();");
        }
    }

 附:全部代码

Html部分

Html代码部分

 

cs部分:

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;
using System.Drawing;

public partial class ToolTip : System.Web.UI.Page
{
    //private DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
              BindData();
        }
       
    }
private DataTable dt;
    private void BindData()
    {
        SqlConnection conn = new SqlConnection("server=192.168.2.3;database=northwind;user id=sa;pwd=imd2006");
        string sql = "select  CustomerID, CompanyName, ContactTitle,Country, City, Address,PostalCode,Phone,Fax from Customers";
        try
        {

            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            dt = new DataTable();
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (SqlException sql_e)
        {
                    }
        catch (Exception ee)
        {
                    }
        finally
        {
            conn.Close();
        }
    }
  
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        //首先检查,当前的行是否属于datarow类型的行,
        //因为象gridview中的headerrow,footerrow等行,并不包含实际的数据,因此,
        //我们不需要使用headerrow和footerrow
        {
            string id = DataBinder.Eval(e.Row.DataItem, "CustomerID").ToString();//获取字段CustomerID
            if (id == "ALFKI")//判断CustomerID是否为ALFKI,如果是则修改该行的背景色为Red
            {
                e.Row.BackColor = Color.Red;
            }
            /**e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='blue'");

            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");**/

            e.Row.Attributes.Add("onmouseover",
"this.oldcolor=this.style.backgroundColor;this.style.backgroundColor='#C8F7FF';");
            e.Row.Attributes.Add("onmousemove",
   //"Show('" + dt.Columns[3].ToString() + "','"
   //                       + dt.Columns[4].ToString() + "','"
   //                       + dt.Columns[5].ToString() + "','"
   //                       + dt.Columns[6].ToString() + "','"
   //                       + dt.Columns[7].ToString() + "','"
   //                       + dt.Columns[8].ToString() + "');");

   "Show('" + e.Row.Cells[3].Text.ToString() + "','"
                          + e.Row.Cells[4].Text.ToString() + "','"
                          + e.Row.Cells[5].Text.ToString() + "','"
                          + e.Row.Cells[6].Text.ToString() + "','"
                          + e.Row.Cells[7].Text.ToString() + "','"
                          + e.Row.Cells[8].Text.ToString() + "');");


            e.Row.Attributes.Add("onmouseout",
    "this.style.backgroundColor=this.oldcolor;Hide();");
        }
    }
    protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    {
        //int i=GridView1.PageIndex+1;
        //int j=GridView1.PageCount;
        //label1.Text = i.ToString() + "-" + j.ToString();
        //BindData();
        int i = GridView1.PageIndex - 1;
        GridViewRow row = GridView1.BottomPagerRow;
        Label l = (Label)row.Cells[0].FindControl("Label1");
        l.Text = "当前第" + i.ToString() + "页-总共" + GridView1.PageCount.ToString() + "页";
         
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if ((GridView1.PageIndex >= 0) && (GridView1.PageIndex < GridView1.PageCount))
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindData();
        }
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        int i = int.Parse(TextBox1.Text);
        if ((i >= 0) && (i < GridView1.PageCount))
        {
            GridView1.PageIndex = i-1;
            BindData();
        }
        if (i < 0)
        {
            GridView1.PageIndex = 0;
            BindData();
        }
        if (i > GridView1.PageCount)
        {
            GridView1.PageIndex = GridView1.PageCount;
            BindData();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex > 0)
        {
            GridView1.PageIndex = 0;
            BindData();
        }
        else
        {
                  }

    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex <GridView1.PageCount)
        {

            GridView1.PageIndex = GridView1.PageCount;
            BindData();
        }
        else
        {
                    }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex > 0)
        {
            GridView1.PageIndex = GridView1.PageIndex - 1;
            BindData();
        }
        else
        {
                   }
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        if (GridView1.PageIndex < GridView1.PageCount)
        {
            GridView1.PageIndex = GridView1.PageIndex + 1;
            BindData();
        }
        else
        {
                    }

    }
    protected void Button6_Click(object sender, EventArgs e)
    {

//获取Geridview中pager template中的textbox
        GridViewRow row = GridView1.BottomPagerRow;
        TextBox t = (TextBox)row.Cells[0].FindControl("TextBox2");
       /t.Text = "Hello";
        //GridView1.PageIndex = GridView1.PageIndex + 1;
        //    BindData();
    }
    protected void Button7_Click(object sender, EventArgs e)
    {
        GridView1.PageSize=int.Parse(TextBox1.Text);
        BindData();
    }
    protected void B1_Click(object sender, EventArgs e)
    {
       
    }
}

 

 
原创粉丝点击