zoukankan      html  css  js  c++  java
  • 扩展CheckBoxList实现选中绑定

    CheckBoxList中有DataTextField和DataValueField可以用于设置绑定时的绑定对象属性,但是可惜针对CheckBoxList却没有办法直接绑定一个Item是否被选中。于是我打算扩展一下CheckBoxList,使得该控件可以绑定Checked状态。具体做法是这样的:

    (1)新建一个Web服务器控件项目,添加Web服务器控件类CheckBoxListWithCheckBind。

    (2)将该类继承自CheckBoxList。

    public class CheckBoxListWithCheckBind : CheckBoxList

    (3)增加属性DataCheckedField,用于指定绑定Checked状态的属性名字符串。

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public string DataCheckedField
    {
    get
    {
    String s = (String)ViewState["DataCheckedField"];
    return ((s == null) ? String.Empty : s);
    }
    set
    {
    ViewState["DataCheckedField"] = value;
    }
    }

    (4)增加BindChecked方法,用于绑定CheckBoxList中的每个Item的Selected属性,这里使用Items.FindByValue方法来找Item的,这里认为每个Item的Value是不同的。如果是Item的Text是不同的,那么也可以使用Items.FindByText方法。

     private void BindChecked()
    {
    var dataSource = this.DataSource as IEnumerable;
    if(dataSource==null)
    {
    return;
    }
    foreach (object obj2 in dataSource)
    {
    var value = DataBinder.GetPropertyValue(obj2, DataValueField, null);
    ListItem item = this.Items.FindByValue(value);
    if (DataCheckedField.Length > 0)
    {
    item.Selected = Convert.ToBoolean(DataBinder.GetPropertyValue(obj2, DataCheckedField, null));
    }
    }
    }

    (5)重写OnDataBinding方法,在基类的OnDataBinding方法后调用前面写的BindChecked方法。

    protected override void OnDataBinding(EventArgs e)
    {
    base.OnDataBinding(e);
    BindChecked();
    }

    具体的代码如下:

    完整代码

    接下来的使用方法就很简单了,直接在aspx页面上写该控件的DataCheckedField属性既可:

    <cc1:CheckBoxListWithCheckBind ID="cbxl" runat="server" DataTextField="CompanyName" DataValueField="CompanyCode" DataCheckedField="IsChecked">
    </cc1:CheckBoxListWithCheckBind>
    【本文章出自博客园深蓝居,转载请注明作者出处,如果您觉得博主的文章对您有很大帮助,欢迎支付宝(studyzy@163.com)对博主进行打赏。】
  • 相关阅读:
    Microsoft Enterprise Library
    TCP拥塞控制算法内核实现剖析(三)
    Linux内核链表实现剖析
    sk_buff 剖析
    TCP拥塞控制算法内核实现剖析(一)
    set time zone Ubuntu
    xml listview
    VSTO rtm assembly
    Assembly and ActiveX
    input a long sentence in a single line of textbox
  • 原文地址:https://www.cnblogs.com/studyzy/p/1538039.html
Copyright © 2011-2022 走看看