Web 数据绑定

一. 单向数据绑定:
   简单来说就是ASP.NET在运行时完成了页面的动态编译,并解析页面的各种服务器端代码,包括数据绑定语法。而数据绑定的语法虽是一些<%# %>代码块,在生成的代码中,仍然使用了服务器端控件以及在DataBinding事件调用DataBinder.Eval方法来完成数据的绑定工作。所有的数据绑定模板控件都使用了这样的机制来进行数据的单向绑定. 这种情况下我们得到的数据不能回发给服务器, 即无法自动完成数据的更新和提交工作.
一般单向数据绑定有下列几种情况(以实例说明):

1. 绑定变量
  (1) xhtml
        ...
         ="<%# Name %>" Font-Names="隶书" ForeColor="Red">
         ="<%# LoginTime %>" Font-Names="隶书" ForeColor="Red">
        ...

   (2) .cs
   public partial class _Default : System.Web.UI.Page
   {
    //此处申明并赋值
    public string Name="admin";
    public DateTime LoginTime = DateTime.Now;
    protected void Page_Load(object sender, EventArgs e)
    {
        //必须声明整页绑定
        Page.DataBind();
    }
   }

2.绑定集合
 (1) xhtml
  ...
     
          =<%# ItemList %> >
     

  ...

 (2) .cs
 public partial class _Default : System.Web.UI.Page
 {
    protected ArrayList ItemList = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ItemList.Add("星期一:Monday");
            ItemList.Add("星期二:Tuesday");
            ItemList.Add("星期三:Wednesday");
            ItemList.Add("星期四:Thursday");
            ItemList.Add("星期五:Friday");
            ItemList.Add("星期六:Saturday");
            ItemList.Add("星期日:Sunday");
            this.DropDownList1.DataBind();
        }
    }
  }

3.绑定表达式
  (1) xhtml
   ...                          
      求整数1—10的总和及平均数
      总和=<%# sum %>
      平均数=<%# sum/10 %>
  
   ...
 
   (2) .cs
   public partial class _Default : System.Web.UI.Page
   {
    protected int sum = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            sum = GetSum();
            Page.DataBind();
    }
    protected int GetSum()
    {
        for (int i = 0; i <= 10; i++)
        {
            sum += i;
        }
        return sum; 
    }
   }

4.绑定方法
  (1) xhtml
  ...
 
           
             绑定方法结果
           

           
             数字:<%# Container.DataItem%>
             绝对值为:<%# AbsoluteValue((int)Container.DataItem)  %>
           

 
  ...
 
  (2) .cs
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ArrayList numbers = new ArrayList();
            numbers.Add(8);
            numbers.Add(-8);
            DataList1.DataSource = numbers;
            DataList1.DataBind();
       
        }
       
    }
    public int AbsoluteValue(int number)
    {
        if (number > 0)
            return number;
        else if (number < 0)
            return -number;
        else
            return 0;
    }
  }

5. .Eval() 方法进行单向(只读)数据绑定
   (1) xhtml
    
       
        显示商品信息
          商品编号
          商品名称
           商品说明
            商品价格
         

         
             '<%# Eval("GoodsID") %>' runat =server>
             '<%# Eval("GoodsName") %>' runat =server>
             '<%#DataBinder.Eval(Container.DataItem,"GoodsIntroduce") %>' runat =server>
             '<%#Eval("GoodsPrice","${0}") %>' runat =server>
                              ImageUrl='<%# Eval("GoodsPhoto") %>' runat="server"/>           
         

      

   (2) .cs
   public partial class Repeater : System.Web.UI.Page
   {
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获得数据库连接
            SqlConnection myConn = DBClass.GetConnection();
            myConn.Open();
            string SqlStr = "select * from tb_GoodsInfo";
            SqlDataAdapter da = new SqlDataAdapter(SqlStr, myConn);
            //生成DataSet对象并填充数据
            DataSet ds = new DataSet();
            da.Fill(ds, "GoodsInfo");
            //将Repeater控件进行数据绑定
            Repeater1.DataSource = ds.Tables["GoodsInfo"].DefaultView;
            Repeater1.DataBind();
        }

    }
    public SqlConnection GetConnection()
    {
        string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        SqlConnection myConn = new SqlConnection(myStr);
        return myConn;
    }
 
  }

 

6.将 DropDownList 控件绑定到GridView 控件中
  (1)  xhtml
  asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                        Font-Size="9pt" ForeColor="#333333" GridLines="None">
                       
                       
                           
                           
                           
                               
                               

                                DataTextField="SellState" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
                                   
                               

                           
                       
                       
                       
                       
                       
                       
  

  (2) .cs
  public partial class _Default : System.Web.UI.Page
  {  
    protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList ddl;
        if (!IsPostBack)
        {
            string sqlstr = "select * from tb_SellBook";
            SqlConnection myConn = GetConnection();
            SqlDataAdapter da = new SqlDataAdapter(sqlstr, myConn);
            DataSet ds = new DataSet();
            myConn.Open();
            da.Fill(ds,"tb_SellBook");
            GridView1.DataSource = ds.Tables["tb_SellBook"].DefaultView;
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                DataRowView mydrv = ds.Tables["tb_SellBook"].DefaultView[i];
                if (Convert.ToString(mydrv["SellState"]).Trim() == "畅销")
                {
                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                    ddl.SelectedIndex = 0;
                }
                if (Convert.ToString(mydrv["SellState"]).Trim() == "一般")
                {
                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                    ddl.SelectedIndex = 1;
                }
                if (Convert.ToString(mydrv["SellState"]).Trim() == "滞销")
                {
                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                    ddl.SelectedIndex = 2;
                }
            }
            myConn.Close();
        }
    }
    public SqlConnection GetConnection()
    {
        string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        SqlConnection myConn = new SqlConnection(myStr);
        return myConn;
    }
    public SqlDataReader ddlbind()
    {
        string sqlstr = "select distinct SellState from tb_SellBook";
        SqlConnection myConn = GetConnection();
        SqlCommand myCmd = new SqlCommand(sqlstr, myConn);
        myConn.Open();
        return myCmd.ExecuteReader();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            DropDownList ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
         
           Response.Write("

  • " + GridView1.Rows[i].Cells[1].Text + ":" + ddl.SelectedItem.Text + "
    ");
            }
        }
      }


    二. 双向数据绑定(可写)
        在.NET 2.0中新增了双向的数据绑定方式,主要用在GridView,DetailsView,FormView等数据容器控件中,结合DataSourceControl就可以非常轻松的完成数据的更新和提交工作,而不需要我们手工去遍历输入控件的值。尤其DataSource控件的使用在很大程度上让开发人员工作量大大减少. 虽然有很多时候它促使程序吊不愿意(不用)去了解数据的更新和提交操作内部工作原理, 致使很多 "有志青年" 十分抵触它. 但是我需要说的是, 如果你了解了它的工作原理, 运行机制, 然后再使用它是不是会大大提高我们的开发效率呢?
       ASP.NET在模板中双向绑定字段,是通过<%# Bind() %>这样的语法实现.如下:
        
       
        
          
                
               姓名:
              
     
                
               '<%# Bind("name") %>'>
              

             
                
               性别:
              
     
                
               '<%# Bind("gender") %>'>
              

          

       
     
     

     

     

      

  • 你可能感兴趣的:(Web 数据绑定)