如何查找当前页面元素---DataList

以下是一个比较特殊的情况,看下图

image

需求:点击相应Button时,隐藏相关GridView

解决思路:1.首先确定当前点击button,是哪一个button

                  2.获取当前点击button的对象(即可进行相关的操作)

遇到问题:因为GridView,Button都是套在DataList中的,所以你无法手动确定当前button的位置?

解决方法:首先在MasterPage页面要定义一个属性

                  MasterPage Page:

       private static Object master;

        /// <summary>
        /// 此属性用于:保存Master对象,以提供Find Control in the Master Page
        /// </summary>
        public static Object PageMaster {
            get { return master; }
            private set { master = value; }
        }

                  A Page:

                  protected void Button_Click ( Object sender , EventArgs e ) {

                       Button button = FindPageElementByItemIndex<Button>( sender , "buttonID" );

                        //可以对Button进行相应操作

                       GridView gridView = FindPageElementByItemIndex<GridView>( sender , "gridViewID" );

                        //可以对GridView进行相应操作(gridView.Visible = true, etc)

                  }

        private T FindPageElementByItemIndex<T> ( Object sender , String findTarget ) where T : class {

         ///确定当前Button在DataList中的位置
         Int32 curItemIndex = ( ( sender as Control ).BindingContainer as DataListItem ).ItemIndex;

         ///查找当前Button 的对象

         ///cphMain---ContentPlaceHolderID

         ///searchResultPage --- UserControl  ID (当然如果你没有把DataList在UserControl中,这个可以不用)

         ///dlSearchResult  --- DataList ID

         return ( ( ( MasterPage.PageMaster as MasterPage ).FindControl( "cphMain" )
                                                                  .FindControl( "searchResultPage" )
                                                        .FindControl( "dlSearchResult" ) as DataList ) )
                                                  .Items[curItemIndex].FindControl( findTarget ) as T;
         }

posted @ 2008-07-30 09:47  RicoRui  阅读(706)  评论(0编辑  收藏  举报