数据的查询与展示

一、GrilView是一个数据源绑定控件,对于任何一个这样的控件来说在绑定控件的时候有两点我们需要注意:

1>     当绑定的是值类型的对象的时候,直接绑定就可以了

    List<string> list = new List<string>();

        list.Add(3);

        list.Add(5);

        list.Add(6);

        this.GridView2.DataSource = list;

2>     当绑定的是引用类型的对象的时候,我们需要使用绑定方法DataBind()才可以完成绑定

     List<Stu> list = new List<Stu>();

        list.Add(new Stu(22,"df"));

        list.Add(new Stu(25,"gg"));

        list.Add(new Stu(24,"n"));

        this.GridView2.DataSource = list;

this.GridView2.DataBind();

 

二、首先我们来看看在asp.net中如何去绑定GrilView

  1>可以直接手动不通过编码的方式一点点视图配置数据源,其实这也是最起初的配置方式,后面要讲到的配置方式刚开始为了方便起见都要先视图去配置,只不过去掉一些不必要的东西而已,当然了,如果你对GirlVIew的绑定源码很清楚,那么也可以手动写。

    注:如果在后台代码中,比如分页,在下一页的时候需要重新绑定的时候,可以将ObjectDataSource的ID重新绑定到GrilView中即可

        this.GridView1.DataSourceID = this.ObjectDataSource2.ID;

 

2>通过编码的方式在后台代码中绑定,为了方便,先按第一种方式绑定好,然后把在页面中将绑定的代码删掉即可

       this.GridView1.DataSource = UserManager.GetAllUser();

        this.GridView1.DataBind();

  上面是两种常用的绑定方式,其他方式不在多说

 

三、GrilView中的7中数据绑定列类型

1>BoundFiled:用于显示普通文本,也是默认的绑定方式,一般自动生成的类型就是该类型,需要注意的是该类型可以设置字段的格式,通过DataFormatString属性:比如日期:{0:yy-mm-dd},货币:{0:c},数字:{0:d}等,但是需要设置hemlCode为false才可以,否则设置无效,或者采用另外一种方式<%#  string.Format("{0:C}",GetPrice(eval_r("unitPrice").ToString()))%>!

 

2> TemplateFileld:以模板的形式自定义数据绑定列的内容,它比较灵活,添加的方式有两种:直接添加TemplateFileld或着将现有的字段转换为模板字段,很好实用,但是有几点需要注意:

                 绑定的时候或用用到Bind和Eval两个方法,这两种方法有着本质的区别:Bind支持数据行的读写等操作,是双向数据绑定,是回发到服务器的,通常与输入文件TextBox一起使用,达到更新数据的目的

           Eval它只支持只读的方法,单项的不会提交回服务器,相当于readonly.

 

Eval还有一个重载的方法'<%# eval_r("Category.Name","{0:dd/MM/yyyy}")%>

括号里面的是类的属性名

3> ButtonFiled: 是个按钮,可以转化成三种普通按钮方式:button,LinkButton,imgButton

                那么它是用来解决怎么问题的呢?

                假如有两列这样的按钮,而且实现不同的操作,那该怎么办呢?这个时候就可以它了,这个时候我们可以设定一下按钮的commandName属性,该属性表示按钮命令的名字,并适当的用到了CommandArgument方法,这个通常在代码中绑定ID,那么具体怎么操作呢

          具体实现的方式就是找到GrilView的RowCommand事件

                 if(e.CommandName=="select")

                 {

                    int Id = int.Parse(e.CommandArgument.ToString();

                     通过id去删除,修改或其他操作

  }

这种方法是做常用,最保障的一个方法,推荐使用这种方法!

3>     CommandField:和ButtonFiled查不多,他创建了命令按钮的功能,相比而言他是个特殊的字段,显示了在数据绑定控件中的执行选择,编辑,插入或删除操作的命令,自动生成命令,主要用法有下面两种:

A 视图配置删除修改等方法(注意方法参数是一个实体),然后将grilView的dataKeyName设为他们的参数,一般都是ID,然后就可以进行操作,如果没用找到相关方法,可以在重新绑定一次

B 假如没有通过视图绑定相关的方法,而且绑定的时候是通过编码绑定的,而不是视图绑定的时候,这个时候我们先将grilView的dataKeyName的值设置好,然后再GrilView的Rowdeleting或RowUpdating方法中获得主键,调用业务逻辑层的相关方法,即可!

  获得主键的方法:

  This.GrilView.DataKeys[e.RowIndex].Value;

  如果Id也被绑定了,也可以通过另外一种方式获得

  this.GridView2.Rows[e.RowIndex].Cells[2].Text

  如果Id是放到web的某个控件中的话,也可以

  this.GridView2.Rows[e.RowIndex].FindControl(“控件名称”).Value;

  然后调用相关方法即可

下面看一个例子:

页面代码:

 

View Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  
            Width="681px" 
            DataKeyNames="customid"  EmptyDataText="没有可显示的数据记录。" 
            HeaderStyle-Height="25" RowStyle-Height="20" 
        
            HeaderStyle-BorderColor="Black" AllowPaging="True"  PagerStyle-BorderColor="White"
            onpageindexchanging="GridView1_PageIndexChanging" 
            onrowediting="GridView1_RowEditing" 
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowupdating="GridView1_RowUpdating" onrowdeleting="GridView1_RowDeleting" 
            >
             <PagerSettings FirstPageText="首页" LastPageText="末页"  
                 Mode="NextPreviousFirstLast" NextPageText="下一页" PreviousPageText="上一页" />
<RowStyle Height="20px"></RowStyle>
            <Columns>
                <asp:BoundField DataField="customName" HeaderText="姓名" ReadOnly="True" 
                    SortExpression="customName" ItemStyle-BorderColor="Black"  
                    HeaderStyle-BorderColor="Black">
<HeaderStyle BorderColor="Black"></HeaderStyle>

<ItemStyle BorderColor="Black"></ItemStyle>
                </asp:BoundField>
                <asp:TemplateField HeaderText="所属单位" SortExpression="customUnit">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("customUnit") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("customUnit") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <HeaderStyle BorderColor="Black" />
                    <ItemStyle BorderColor="Black" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="身份证" SortExpression="customCard">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("customCard") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("customCard") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <HeaderStyle BorderColor="Black" />
                    <ItemStyle BorderColor="Black" />
                </asp:TemplateField>
                <asp:BoundField DataField="selectNumDate" HeaderText="时间"  DataFormatString="{0:yyyy.MM.dd}"
                    SortExpression="selectNumDate" ItemStyle-BorderColor="Black" 
                    HeaderStyle-BorderColor="Black">
<HeaderStyle BorderColor="Black"></HeaderStyle>

<ItemStyle BorderColor="Black"></ItemStyle>
                </asp:BoundField>
                 <asp:BoundField DataField="selectNum" HeaderText="号码" ReadOnly="True" 
                    SortExpression="customName" ItemStyle-BorderColor="Black"  
                    HeaderStyle-BorderColor="Black">
<HeaderStyle BorderColor="Black"></HeaderStyle>

<ItemStyle BorderColor="Black"></ItemStyle>
                </asp:BoundField>
                <asp:CommandField HeaderText="操作" ShowEditButton="True"  />
                <asp:CommandField />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
            </Columns>

<PagerStyle BorderColor="White"></PagerStyle>

<HeaderStyle BorderColor="Black" CssClass="STYLE7" Height="25px"></HeaderStyle>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

后台cs代码:

 

View Code
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void bind()
    {
        string sqlstr = "select * from tb_Custom ";
        DataTable customList = DBHelp.GetTable(sqlstr);
        GridView1.DataSource = customList;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        bind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string id = this.GridView1.DataKeys[e.RowIndex].Value.ToString(); 

        //根据号码修改信息
        
        string customUnit = ((TextBox)(this.GridView1.Rows[e.RowIndex].FindControl("TextBox1"))).Text;
        string cNum = ((TextBox)(this.GridView1.Rows[e.RowIndex].FindControl("TextBox2"))).Text;

        StringBuilder strSql = new StringBuilder();
        strSql.Append("update tb_Custom set customUnit=@customUnit,customCard=@customCard");
        strSql.Append(" where customid=@customid");
        OleDbParameter[] paras = new OleDbParameter[] { 
        new OleDbParameter("@customUnit",customUnit),
        new OleDbParameter("@customCard",cNum),
        new OleDbParameter("@customid",id)
        };
        int result = DBHelp.Query(strSql.ToString(), paras);
      //  bind();
        Response.Redirect("Default.aspx");
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
        string sqldel2 = "delete from tb_Custom where customid=" + id;
        DBHelp.Query(sqldel2);
        bind();
    }
}

 

4>     HyperLinkField可以将绑定的字段以超链接的形式显示出来

通过DataNavigateUrlFields绑定id,DataNavigateUrlFormatString设置格式

<asp:HyperLinkField DataNavigateUrlFields="Id"

                DataNavigateUrlFormatString="UserDetails.aspx?id={0}" Text="详细" />

5> ImageField:和上面的用法差不多,所呈现的表格中显示图片列,一般绑定的都是图片的路径

         <asp:ImageField DataImageUrlField="ISBN"

                    DataImageUrlFormatString="“~/images/bookcover/{0}.jpg”" HeaderText="图片">

 </asp:ImageField>

6> CheckBoxField: 可以使用复选框的形式显示布尔类型的数据,只有当该控件中有布尔类型的数据时才可以使用

 

有了上面的几种数据字段绑定类型,字段就可以很好的绑定到控件上了!

GrilView中绑定数据的时候有时候需要限制的显示,就是所谓绑定业务逻辑层带带参数显示所有信息的方法,那么他的绑定就和绑定所有的信息有所不同:

 

四、GirlView修改,删除确认功能

这个有两种方式给予提示确认:

1>     在按钮控件中直接使用onclientClick

   <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"

                            CommandName="select" Text="按钮" OnClientClick="return comfirm('是否确定删除')" ></asp:LinkButton>

 2> 在RowDataBound中去设置

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

          {

              if (e.Row.RowType == DataControlRowType.DataRow)

                {

                    LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");

                    l.Attributes.Add("onclick", "javascript:return " +

                   "confirm('确认删除要删除吗?')");

          }

       

                 

 

五、下面看看GirlView的分页

   1> 我们知道GirlView有自带的分页功能,当我们是通过视图去绑定控件的时候直接启用自带的分页功能,就可以了,不必多说

2> 当我们是通过编码的方式绑定用户控件的时候,那么这个时候你启用分页功能是不行的,这个时候需要相关操作

       protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
         {
            GridView1.PageIndex = e.NewPageIndex;
            this.GrilView1.DataBind();
         }

  3> AspNetPager与PagedDataSource共同完成分页

      首先讲一下PagedDataSource是asp.net中一个分页类,该类封装了数据绑定控件与页面相关的一些属性,大概讲一下:

     CurrentPageIndex:这个代表当前的页数,由我们来指定

     PageCount:这个在后面可以自动获取的总页数

     Count:总记录数,只读

     PageSize:这个需要我们来指定,代表的是每页显示的记录数

     AllowSource:控件是否有自动分页的功能

     其次我们来看看如何让第三方空间aspnetPager与PageDataSource一起很好的完成分页

     我们来思考一个问题,假如点击第二页的时候,我们定义的那个page页数怎么才会被记录下来并且+1呢,就是说怎么在同一个页面中回传的过程中保持原来的值不变呢?这个时候我们就可以用到ViewState这个对象了,它就是用来保持一个页面在回传的过程中记录数据的类,知道了这个对下面的分页很重要

页面添加:

 <div style="text-align:center">
                            <webdiyer:AspNetPager ID="AspNetPager1" runat="server" AlwaysShow="True"
            FirstPageText="第一页" LastPageText="最后一页" NextPageText="下一页"
            PrevPageText="前一页" UrlPaging="True" onpagechanging="AspNetPager1_PageChanging">
        </webdiyer:AspNetPager>
&nbsp;</div>

后台代码:

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            Pager = 0;

            Datebind();

        }

}

public void Datebind()

    {

        PagedDataSource pdsBooks = new PagedDataSource();

        pdsBooks.DataSource = BookManager.GetBookInfoBySQL();

        AspNetPager1.RecordCount = pdsBooks.Count;

        pdsBooks.AllowPaging = true;

        pdsBooks.PageSize = 4;

        pdsBooks.CurrentPageIndex = Pager;

        this.lblPage.Text = "第" + (pdsBooks.CurrentPageIndex + 1).ToString() + "页 共 " + pdsBooks.PageCount.ToString() + "页";

        SetEnable(pdsBooks);

        DataList1.DataSource = pdsBooks;

        DataList1.DataBind();

    }

   private int Pager

    {

       get{

          return Convert.ToInt32(ViewState["Page"]);

          }

        set{

           ViewState["Page"] =value;

        }

    }

上面是当第一次加载页面的时候,我们定义的一个Pager变量,用ViewState记录回传后的页面值,然后绑定数据

    protected void LinkButton1_Click(object sender, EventArgs e)

    {

        Pager--;

        Datebind();

    }

    protected void LinkButton2_Click(object sender, EventArgs e)

    {

        Pager++;

        Datebind();

    }

   上面是实现的上一页和下一页,其实在aspnetpager中已经有了,在这里顺便写一下

    protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)

    {

        Pager = e.NewPageIndex-1;

        Datebind();

    }

}

  上面是AspNetPager的分页,那么为什么-1呢,因为pageDateSource的pageSize都是从0开始的,这也是为什么刚开始就让pager的值等于0的原因

    public void SetEnable(PagedDataSource pdsBooks)

    {

        this.LinkButton1.Enabled = true;

        this.LinkButton2.Enabled = true;

        if(pdsBooks.IsFirstPage)

        {

            this.LinkButton1.Enabled = false;

        }

        if(pdsBooks.IsLastPage)

        {

            this.LinkButton2.Enabled = false;

        }

    }

 上面的判断是不是首页或最后一页而所作的逻辑处理

 这就是目前比较简单的分页方式,可以灵活使用,如果绑定的方法中还有参数的时候,我们也需要用ViewState将参数记录下来!

4> Sql语句分页

用sql语句进行分页是每个面向对象语言开发分页功能的一个通用的方法,下面我们就来简单说一下

假如数据表中有16行记录,在前台一页当中我们只让现实4条,那么就是说需要分成四页,那么这个怎么去实现呢?

分析:首先我们会只让它读取4条记录,然后到第二页的时候,我们也会读取4条记录,但是是出去前面4条记录的其余记录的前4条记录,同样到第三页的时候我们会读取除了前8个之后余下所有记录的前4条记录…,知道这个原理之后分页就变的很简单了

那么sql语句就可以这样写了:

Select top 4 * from Student where id not in(select top ((page - 1) * 4) * from Student )

我们现在来写一个通用的分页读取数据的方法

Page:代表是当前页

PageSize:代表每页显示的记录数

Public static IList<Student> GetStudent(int  Page, int PageSize)

{

   Int line=0;//要除去的记录数

   If(Page>1)

{

   Line=(Page-1)*PageSize;

}

String sql=“Select top PageSize * from Student where id not in(select top line ** from Student )”;

//子语句一定要于外面的语句一样,否则会出现不一致的情况

}

有时候为了统计所有记录数,可以用来获取或者判断等,我们还需要读取所有记录

我们发现当总记录数/每页显示的记录数=偶数 那么页数就是这个偶数

否则如果是奇数,那么总页数就是(奇数+1)

所以我们有时候需要判断两次。

现在有一个方法可以让我们不用判断

总页数=((count-1)/pagesSize)+1;

2 以下是下拉分页

思路很简单,如果将装载下拉列表的循环放到load事件中,那么是肯定读不出gridview总页码的!

先考虑页面以及控件的执行顺序我们就能发现,load事件是发生最前面,其次读取数据库,然后绑定给GridView,在绑定的过程中又有先按照控件分页的相关限制得到页码!!

所以,我们可以知道,分页肯定应该是在GridView的数据被绑定之后才发生!!

说到这里我想应该是知道了,这个装载下拉列表的事件肯定是应该发生在GridView1_DataBound事件中的了!

代码没什么技术含量,很简单!!如下:
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {//判断页是否第一次载入,

       for (int i = 1; i <= GridView1.PageCount; i++)
            {//从1开始循环到页的最大数量
                DropDownList1.Items.Add(i.ToString());//填充到下拉列表
            }
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.PageIndex =Convert.ToInt32(DropDownList1.SelectedValue)-1;
        //因为页码其实是从0开始的,而我们为了看起来直观,所以从1开始,这样来说我们就必须减1才是真实的页码
    }

然后再前台调用这些方法即可完成分页功能,具体的情况具体对待,灵活使用

 

六、GirlView的光棒效果

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");

            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");

        }

    }

七、GrilView的多选效果

         <asp:TemplateField HeaderText="全选">

                <HeaderTemplate>

                    <input ID="Checkbox1" type="checkbox" onclick="GetChkState(this.checked)" />全选

                </HeaderTemplate>

                <ItemTemplate>

                    <asp:CheckBox ID="CheckBox2" runat="server" />

                </ItemTemplate>

            </asp:TemplateField>

Js事件

<script type="text/javascript">

    function GetChkState(isChecked) {

        var chks = document.getElementsByTagName_r("input");

        for (var i = 0; i < chks.length; i++) {

            if (chks[i].type == "checkbox") {

                chks[i].checked = isChecked;

                 

                 }

        }

    }

</script>          

如果在后台我们要执行所选的项,然后对其删除和修改

那么我们可以先遍历这些checkBox1,然后判断哪个选上了,就执行相关操作

如:

public void ChangStatus(int status)

    {

        for (int i = 0; i < this.GridView1.Rows.Count; i++)

        {

            CheckBox ch = (this.GridView1.Rows[i].FindControl("Checkbox2")) as CheckBox;

            if (ch.Checked == true)

            {

                Response.Write(this.GridView1.Rows[i].Cells[0].Text);

                UserManager.updateState(Convert.ToInt32(this.GridView1.Rows[i].Cells[0].Text), status);

            }

        }

        string name = this.DropDownList1.SelectedItem.Value;

        this.GridView1.DataSourceID = this.ObjectDataSource2.ID;

    }

一般而言,对于多行多列的展示,我们会选择GirlView显示,对于单行多列,或者是多行单列的数据展示,我们则会选择DataList和Repeater

他们的大部分用法和GirlView差不多,只不过他们有自己的模板,需要手动编辑布局,内容模板,分割模板等

注:获得编号可以通过自带的属性

   <%# Container.DataItemIndex+1 %>

posted @ 2011-03-02 21:21  双魂人生  阅读(1154)  评论(0编辑  收藏  举报