使用接口来获取 DataSource 对象中的数据

    在开发单表数据和主从表数据处理控件时,个人感觉在控件内部获取数据源中的数据是比较麻烦的,而在外部则是非常简单。也就是说当在外部获取数据源时,因为 DataSource 指定的对象是自己清楚它是 DataSet、DataTable或DataView等,而对于控件的开发者来说这些是未知的,所以要取得 DataSource 对象中数据只能依靠接口。下面的是单表数据处理控件在用户点击编辑按钮时获取用户所选行数据的代码,在主从表中略有不同,不过原理基本一样。 

   internal Hashtable GetEditData()
  {
   IEnumerable enumerable = GetResolvedDataSource();
   
   if( enumerable != null )
   {
    IEnumerator rows = enumerable.GetEnumerator();

    int i=0;
    Hashtable result = null;
    while( rows.MoveNext() )
    {
     if( i != this.EditItemIndex )
     {
      i++;
      continue;
     }

     DataRow row = ((DataRowView)rows.Current).Row;
     result = new Hashtable();
     int k = row.ItemArray.Length;

     for( int j=0; j < k; j++ )
      result.Add( row.Table.Columns[j].ColumnName, row.ItemArray[j] );

     break;
    }

    return result;
   }

   return null;
  }

  internal IEnumerable GetResolvedDataSource()
  {
   if( DataSource != null )
   {
    IListSource iListSource = DataSource as IListSource;

    if( iListSource != null )
    {
     IList iList = iListSource.GetList();

     if( !iListSource.ContainsListCollection )
      return iList;

     if( (iList != null) && ( iList is ITypedList ) )
     {
      ITypedList iTypedList = (ITypedList)iList;
      PropertyDescriptorCollection collection = iTypedList.GetItemProperties( new PropertyDescriptor[0] );

      if( (collection == null) || collection.Count == 0 )
      {
       throw new HttpException("IListSource 控件不包含任何数据源。");
      }
      
      PropertyDescriptor discriptor = null;

      if( (DataMember == null) || DataMember.Length == 0 )
       discriptor = collection[0];
      else
       discriptor = collection.Find( DataMember, true );

      if( discriptor != null )
      {
       object key = iList[0];
       object val = discriptor.GetValue(key);

       if( (val != null) && val is IEnumerable )
        return (IEnumerable)val;
      }

      throw new HttpException("IListSource 不包含一个名为 " + DataMember + " 的数据来源");
     }
    }

    if( DataSource is IEnumerable )
    {
     return (IEnumerable)DataSource;
    }
   }

   return null;
  }



posted on 2005-05-30 15:40  Easy Company  阅读(2649)  评论(0编辑  收藏  举报

导航