zoukankan      html  css  js  c++  java
  • ASP.NET 数据绑定控件和 Eval方法

    数据绑定 (很早的时候做的笔记)
     
    简单属性
    <%# textBox.txt%>
      Page.DataBind();该方法将数据源绑定到被调用的服务器控件及其所有子控件
            <asp:TextBox ID=”TextBox1” runat=”server” AutoPostBack=”True”
                ontextchanged=”TextBox1_TextChanged”></asp:TextBox>
            <asp:Label ID=”Label1” runat=”server” Text=”<%# TextBox1.Text %>”></asp:Label>
            <br />
            <asp:Label ID=”Label2” runat=”server” Text=””><%= Label1.Text %></asp:Label>
    集合绑定
      <asp:ListBox ID=”ListBox1” runat=”server” DataSource=’<%# t.getList() %>’ ></asp:ListBox>
    t.getList()方法返回一个集合
    集合绑定要使用数据源控件的DataSource属性
    表达式
    <%# (customer.FirstName+””+customer.LastName) %>
    方法结果绑定
    <%# t.getList() %>
    后期绑定 迟绑定



    命名容器
    <%# DataBinder.Eval(Container.DataItem,”max_lvl”,”{0:c}” ) %>
    参数:
    >>>数据项的命名容器Container.DataItem
    >>>数据字段名”max_lvl”
    >>>格式字符串”{0:c}” 可选的可以不加
    格式字符串
    数字格式:
    {0:c} 货币形式:¥100.10
    {0:p}百分数形式:10%
    {0:n}保留小数形式:100.100
    日期格式:
    {0:D}短日期格式 2005年3月24日  
    {0:F} 2005年3月23日 0:00:00
    {0:G} 2005-3-21 0:00:00
    {0:M} 3月23日
    {0:R} Thu, 23 Mar 2005 00:00:00 GMT
    {0:T} 0:00:00
    {0:U} 2005年3月23 日 16:00:00
    {0:Y} 2005年3月
    Repeater控件
    Model

    <asp:Repeater ID="Repeater1" runat="server"
                onitemcommand="Repeater1_ItemCommand">
                <ItemTemplate>
                正常显示的项
                </ItemTemplate>
                <AlternatingItemTemplate>
                交错项
                </AlternatingItemTemplate>
                <HeaderTemplate>
                头模版 ,页眉
                </HeaderTemplate>

            <FooterTemplate>
            页脚
            </FooterTemplate>
            <SeparatorTemplate>
            间隔 ,分格
            </SeparatorTemplate>
    </asp:Repeater>
                            
          
    <asp:Repeater ID="Repeater1" runat="server">
          <HeaderTemplate>
             <b> 模板页眉<br /></b>
          </HeaderTemplate>
          <SeparatorTemplate>
          <hr color=blue size=1 />
          </SeparatorTemplate>
          <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem,"Title") %>
              <br />
          </ItemTemplate>
          <AlternatingItemTemplate>
              <font color="gray">
                  <%# DataBinder.Eval(Container.DataItem,"Title") %>
                  <br />
              </font>
          </AlternatingItemTemplate>
          <FooterTemplate>
             <b> 模板页脚</b></FooterTemplate>
      </asp:Repeater>
                                            
    <%# DataBinder.Eval(Container.DataItem,"Title") %>
    Container 命名容器

    分页数据源::  PagedDataSource //可分页数据源
    Demo

    代码


            
    int pagetCount = Convert.ToInt32(this.Label1.Text);
            SqlConnection con 
    = DB.con;
            SqlDataAdapter sda 
    = new SqlDataAdapter();
            DataSet ds 
    = new DataSet();
            PagedDataSource ps 
    = new PagedDataSource();//可分页数据源
            sda.SelectCommand = new SqlCommand("select top(90) * from books", con);
            
    try
            {
                con.Open();
                sda.Fill(ds, 
    "books");
                ps.DataSource 
    = ds.Tables["books"].DefaultView;//初始化可分页数据源的数据源属性
                ps.AllowPaging = true;//设置为可分页
                ps.PageSize = 10;//设置每页显示多少行数据
                ps.CurrentPageIndex = pagetCount - 1;//设置当前页
                this.Button1.Enabled = true;
                
    this.Button2.Enabled = true;

                
    this.Repeater1.DataSource = ps;//用可分页数据源初始Repeater控件
                this.Repeater1.DataBind(); //绑定   
                if (pagetCount==1)
                {
                    
    this.Button1.Enabled = false;
                }
                
    if (pagetCount == ps.PageCount)
                {
                    
    this.Button2.Enabled = false;
                }
    DataList控件
    实现查看详细信息按钮
    1.    在普通项模板中添加一个按钮 将该按钮的 commandName 属性设置为”select”
    2.    在DataList的ItemCommand 事件中 实现选择行

    代码
        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            
    if (e.CommandName=="select")
            {
                
    this.DataList1.SelectedIndex = e.Item.ItemIndex;
                
    this.DataList1.DataBind();
            }
    }
    3.     在选中项 模板中 显示需要显示的信息
           <SelectedItemTemplate>
            <%# DataBinder.Eval(Container.DataItem,"title") %>
            发行日期:<%# DataBinder.Eval(Container.DataItem,"publishDate","{0:d}") %>
            <%# DataBinder.Eval(Container.DataItem,"contentdescription") %>
            </SelectedItemTemplate>
    GirdView控件

    添加字段页面:

    HyperLinkField 超链接项
    主要属性:

    DataNavigateUrlFields         将要绑定的数据源字段名称
    DataNavigateUrlFormatString   将以get方式提交到目标页面如:BookDetail.aspx?id={0}
    连接后面的?id= 是提交地址 {0} 是占位符
    或者:
    比如将要提交的页面是一个有序的页面它根据表中的ID字段来命名页面名称
    DataNavigateUrlFields       属性为 BookName
    DataNavigateUrlFormatString 属性为 Books/{0}.aspx

    RowDataBound事件 实现鼠标悬停当前行变色

    代码
      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");
          }
      }

    补充内容----转自http://hi.baidu.com/netlmz/blog/item/ec325d22c6d1ce4492580793.html

    字符串格式化:table.AppendFormat(@"<td>{0}</td>",string.Format("{0:C}", Convert.ToInt32(sumMoney)) );

    <%# Eval("finishtime","{0:yyyy-MM-dd}") %>
    在绑定数据时经常会用到这个句程序:

    <%# DataBinder.Eval(Container.DataItem,"xxxx")%>或者

    <%# DataBinder.Eval(Container,"DataItem.xxxx")%>

    微软这种方法的效率更高,但我不常用,我习惯了上一种。

    <%# ((DataRowView)Container.DataItem)["xxxx"]%> 用这种方法首先要在前台页面导入名称空间System.Data,否则会生成错误信息。

    <%@ Import namespace="System.Data" %>

          DataBinder.Eval()可以梆定方法,Text='<%# PBnumber(DataBinder.Eval(Container.DataItem,"photoBookID")) %>后台代码:
    protected string PBnumber(object PBid)
    {

                string str = "[ " + Convert.ToString(PBc.GetInPbkPnum((int)PBid)) + " ] 张";

                return str;
    }

           DataBinder.Eval还可以判断选择,如以性别为例:

    <asp:TemplateColumn HeaderText="性别">
    <ItemTemplate>
    <%# DGFormatSex(Convert.ToString(DataBinder.Eval(Container.DataItem,"xb"))) %>
    </ItemTemplate>
    </asp:TemplateColumn>

       cs里定义DGFormatSex方法
    protected string DGFormatSex(string xb)
    {
    if(xb == "1")
    return "男";
    else
    return "女";
    }

         DataBinder.Eval用法范例

    //显示二位小数
    //<%# DataBinder.Eval(Container.DataItem, "UnitPrice", "${0:F2}") %>

    //{0:G}代表显示True或False
    //<ItemTemplate>
    // <asp:Image Width="12" Height="12" Border="0" runat="server"
    // AlternateText='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "{0:G}") %>'
    // ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "~/images/{0:G}.gif") %>' />
    // </ItemTemplate>

    //转换类型
    ((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)

    {0:d} 日期只显示年月日
    {0:yyyy-mm-dd} 按格式显示年月日
    {0:c} 货币样式

     本文假设你已经了解ASP.NET 1.1的数据绑定(特别是Container这个局部变量)的机制,这里主要分析ASP 2.0数据绑定做了那些改进。

    ASP.NET 2.0 的数据绑定函数Eval()简化掉了ASP 1.1神秘的Container.DataItem,比如数据绑定表达式:

    <%# (Container.DataItem as DataRowView)["ProductName"].ToString() %>

      ASP.NET 1.1简化为:(去掉了类型指定, Eval通过反射实现,本文不再阐述)

    <%# DataBinder.Eval(Container.DataItem, "ProductName").ToString() %>

      ASP.NET 2.0又简化为,去掉了Container局部变量:

    <%# Eval("ProductName") %>

      那么,Page.Eval()又是如何知道"ProductName"是那个数据的属性呢,即Container.DataItem真的消失了吗?

    Eval()是Page的父类TemplateControl的方法

    TemplateControl.Eval()可以自动计算出Container, 机制就是从一个dataBindingContext:Stack堆栈来获取。

    1. 建立DataItem Container 栈:

    在Control.DataBind()中,建立,这样可以保证子控件的DataItem Container始终在栈顶。

    public class Control
    {
    protected virtual void DataBind(bool raiseOnDataBinding)
    {
    bool foundDataItem = false;
    if (this.IsBindingContainer)
    {
    object o = DataBinder.GetDataItem(this, out foundDataItem);
    if (foundDataItem)
    Page.PushDataItemContext(o); <-- 将DataItem压入堆栈
    }
    try
    {
    if (raiseOnDataBinding)
    OnDataBinding(EventArgs.Empty);

    DataBindChildren(); <-- 绑定子控件
    }
    finally
    {
    if (foundDataItem)
    Page.PopDataItemContext(); <-- 将DataItem弹出堆栈
    }
    }
    }

      2. 获取DataItem Container

    public class Page
    {
    public object GetDataItem()
    {
    ...
    return this._dataBindingContext.Peek(); <-- 读取堆栈顶部的DataItem Container,就是正在绑定的DataItem    Container
    }
    }

      3. TemplateControl.Eval()

    public class TemplateControl
    {
    protected string Eval (string expression, string format)
    {
    return DataBinder.Eval (Page.GetDataItem(), expression, format);
    }
    }

      结论:

    从上面看出Page.Eval()在计算的时候还是引用了Container.DataItem,只不过这个DataItem通过DataItem Container堆栈自动计算出来的。我认为Page.Eval()看似把问题简化了,其实把问题搞得更加神秘。

    <%# Eval("C_FromTime","{0:d}") %>
    DateTime.Parse(EquInfo.FindEquInfoByID(Request["id"]).InDate).ToShortDateString()

    标准的Format格式Format Format 模式
    d MM/dd/yyyy 如(2001-3-27)
    D dddd, MMMM dd, yyyy 如(2001年3月27日)
    f dddd, MMMM dd, yyyy HH:mm 如(2001年3月27日 0:00)
    F dddd, MMMM dd, yyyy HH:mm:ss 如(2001年3月27日 0:00:00)
    g MM/dd/yyyy HH:mm 如(2001-3-27 0:00)
    G MM/dd/yyyy HH:mm:ss 如(2001-3-27 0:00:00)
    m, M MMMM dd 如(三月 27)
    r, R ddd, dd MMM yyyy HH’:’mm’:’ss ’GMT’ 如(Mon, 26 Mar 2001 16:00:00 GMT)
    s yyyy-MM-dd HH:mm:ss 好像不能使用
    t HH:mm 如(0:00)
    T HH:mm:ss 如(0:00:00)
    u yyyy-MM-dd HH:mm:ss 如(2001-03-26 16:00:00Z)
    U dddd, MMMM dd, yyyy HH:mm:ss 如(2001年3月26日 16:00:00)
    y, Y MMMM, yyyy 如(2001年3月)
    自定义格式列表Format Pattern Description
    d 如:2001-3-27
    dd 如:27
    ddd 如:星期一
    dddd 如:星期一(全名)
    M 如:三月 27
    MM 如:03
    MMM 如:三月
    MMMM 如:三月(全称)
    y 如:2001年3月
    yy 如:01
    yyyy 如:2001
    gg 如:A.D.
    hh, hh* 如:12
    HH, HH* 如:00
    m 如:三月 27
    mm, mm* 如:00(分钟)
    s 如:2001-03-27T00:00:00
    ss, ss* 如:00(秒)
    t 如:0:00
    tt, tt* 如:上午


  • 相关阅读:
    vs2008将 win32项目改为console项目
    python——pandas技巧(处理dataframe每个元素,不用for,而用apply)
    leetcode计划
    初识Flask——基于python的web框架
    开展论文研究——推荐系统
    c++如何按照map的value进行排序?
    sklearn决策树应用及可视化
    黑客可远程控制!微软紧急修补2个新漏洞,以下系统版本都受影响
    高通推出新的智能手表芯片,为安卓系统注入新的活力
    美国宇航局向有创意的科技小企业支付5100万美元
  • 原文地址:https://www.cnblogs.com/Qbit/p/1693709.html
Copyright © 2011-2022 走看看