ASP.NET控件开发基础(19)

http://tech.ddvip.com   2007年09月02日    社区交流

内容摘要:上两篇讨论了基本数据绑定控件的实现步骤,基本上我们按着步骤来就可以做出简单的数据绑定控件了。过年前在看DataGrid的实现,本来想写这个的,但2.0出了GridView了,再说表格控件实现比较复杂,所以先放着。我们一起打开MSDN来看点别的,当然主题还是离不开数据绑定控件。

  第三类控件为新增控件,显示一个项列表

  要看出不同,则可以根据生成的html代码进行比较

  (3)具体实现

  1.简单实现一个DropDownList,可能就LoadPostData方法稍微复杂点,其他的应该都没什么

public class CustomDropDownList : ListControl, IPostBackDataHandler
  {
  
    [DefaultValue(0),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override int SelectedIndex
    {
      get
      {
        int selectedIndex = base.SelectedIndex;
        if ((selectedIndex < 0) && (this.Items.Count > 0))
        {
          this.Items[0].Selected = true;
          selectedIndex = 0;
        }
        return selectedIndex;
      }
      set
      {
        base.SelectedIndex = value;
      }
    }
  
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
      string uniqueID = this.UniqueID;
      if (uniqueID != null)
      {
        writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
      }
      base.AddAttributesToRender(writer);
    }
  
    protected override ControlCollection CreateControlCollection()
    {
      base.CreateControlCollection();
    }
  
    IPostBackDataHandler 成员#region IPostBackDataHandler 成员
  
    public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
    {
      string[] values = postCollection.GetValues(postDataKey);
      this.EnsureDataBound();
      if (values != null)
      {
        ListItem selectitem = Items.FindByValue(values[0]);
       
        int selectedIndex = this.Items.IndexOf(selectitem);
        if (this.SelectedIndex != selectedIndex)
        {
          //设置selected属性
          base.SetPostDataSelection(selectedIndex);
          return true;
        }
      }
      return false;
    }
  
    public void RaisePostDataChangedEvent()
    {
      OnSelectedIndexChanged(EventArgs.Empty);
    }
  
    #endregion
  }

责编:豆豆技术应用

正在加载评论...