首页 > 代码库 > 自动为DEV GridView控件添加SizeChanged事件

自动为DEV GridView控件添加SizeChanged事件

实现gdv设置的抽象对象,不用每个gdv控件都添加sizechanged事件,只需执行gdc绑定sql函数,在其中会自动添加SizeChanged事件。

 

//2016.5.13 by sngk

        //根据控件大小自动调整GridView列宽模式,尽量使列充满

        //2016.11.19 实现自动添加sizechanged事件

        //该函数只执行一次,在赋值时

        public static void BestFitGridViewColumnsWidth(DevExpress.XtraGrid.GridControl gdc,string sql, int hidecols=0)

        {

            DevExpress.XtraGrid.Views.Grid.GridView gdv = (DevExpress.XtraGrid.Views.Grid.GridView)gdc.Views[0];

 

            //绑定数据

            gdv.GridControl.DataSource = DBFactorySingleton.GetInstance().Factory.GetDataTable(sql);

 

            for (int i = 0; i < hidecols;i++ )

                gdv.Columns[i].Visible = false;

     //添加事件

            gdc.SizeChanged += BestFitDevGrid_Size_Changed_Event;

 

            //虽然每次窗体变化时都会激发sizechange事件,但窗体第一次load时不会触发,所以加一句调整语句

            BestFitGridViewWidth(gdv);

           

        }

 

        //2016.11.19 技术进步,后台为控件添加事件

        public static void BestFitDevGrid_Size_Changed_Event(object sender, EventArgs e)

        {

            //获得gdc对象

            DevExpress.XtraGrid.GridControl gdc=(DevExpress.XtraGrid.GridControl)sender;

 

            //取得gdc的第一个gdv对象

            DevExpress.XtraGrid.Views.Grid.GridView gdv = (DevExpress.XtraGrid.Views.Grid.GridView)gdc.Views[0];

 

            //设置最适合列宽的判断行数

            gdv.BestFitMaxRowCount = 500;

 

            BestFitGridViewWidth(gdv);           

        }

 

        //根据窗体大小判断gdv最合适大小

        public static void BestFitGridViewWidth(DevExpress.XtraGrid.Views.Grid.GridView gdv)

        {

            //先设置最小列宽

            gdv.BestFitColumns();

 

            //获取所有列总最小宽度

            int tt = 0;

            for (int i = 0; i < gdv.Columns.Count; i++)

            {

                if (gdv.Columns[i].Visible)

                    tt += gdv.CalcColumnBestWidth(gdv.Columns[i]);

            }

 

            //如果有指示列,加上其宽度

            if (gdv.OptionsView.ShowIndicator)

                tt += gdv.IndicatorWidth;

 

            //根据宽度调整列显示模式

            if (tt < gdv.ViewRect.Width)

                gdv.OptionsView.ColumnAutoWidth = true;

            else

                gdv.OptionsView.ColumnAutoWidth = false;

        }

 

自动为DEV GridView控件添加SizeChanged事件