zoukankan      html  css  js  c++  java
  • Asp.net中慎用Page.DataBind()

    问题代码

    Default.aspx:

    代码
    <asp:DropDownList ID="ddlTradingServiceType" CssClass="s_w90 m-r0" runat="server"
            EnableViewState
    ="false">
            
    <asp:ListItem Value="-1">全部</asp:ListItem>
            
    <asp:ListItem Value="consignment">寄售交易</asp:ListItem>
            
    <asp:ListItem Value="escort">担保交易</asp:ListItem>
            
    <asp:ListItem Value="id">帐号交易</asp:ListItem>
            
    <asp:ListItem Value="api">官方合作交易</asp:ListItem>
            
    <asp:ListItem Value="cardservice">点卡交易</asp:ListItem>
        
    </asp:DropDownList><a href="?ts=nodefine">跳跳</a>

    Default.aspx.cs:

    代码
    protected void Page_Load(object sender, EventArgs e)
            {
                
    if (!string.IsNullOrEmpty(Request.QueryString["ts"]))
                {
                    ddlTradingServiceType.SelectedValue 
    = Request.QueryString["ts"];
                    ddlTradingServiceType.DataBind();
                }
            }

    当页面点击"跳跳"时,页面会报错


    原因在我给dllTradingServiceType.SelectedValue赋值后,调用了DataBind(),而在控件数据绑定的时候,服务会发现dllTradingServiceType的Items集合中没有Value为nodefine的项,故报无效SelectedValue的错误。往往在写程序时我们会给DropDownList控件的SelectedValue赋值一个不存在的Value,如果我们不调用DataBind(),服务器是不会检测项目列表的,故不会出错,事实上这种写法存在问题。MSDN对Page.DataBind()的解释:
    Binds a data source to the invoked server control and all its child controls.

    Remarks
    Use this method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query.

    Note   When called on a server control, this method resolves all data-binding expressions in the server control and in any of its child controls.

    This method is commonly overridden when creating custom templated data-bound controls. For more information, see Developing a Templated Data-Bound Control.

    For more information about data binding to server controls, see Data Binding Expression Syntax.

    作者:Olar Tan
    出处:http://www.cnblogs.com/olartan
    ♪:没有做不到的 只有偷懒而错过的 ♪

  • 相关阅读:
    Linux 模块管理
    python 调试方法
    LFS(Linux From Scratch)学习
    Vim完全教程
    OpenSSL基础知识
    关于jiffies回绕以及time_after,time_before
    十分简便的APK反编译(Mac 版本号 具体解释)
    亚马逊是怎样颠覆商业软件高昂价格这座”柏林墙”的
    Android自己定义控件
    Android基础新手教程——4.1.1 Activity初学乍练
  • 原文地址:https://www.cnblogs.com/olartan/p/1751505.html
Copyright © 2011-2022 走看看