1. 程式人生 > >Devexpress使用之:GridControl控制元件 Devexpress使用之:GridControl控制元件

Devexpress使用之:GridControl控制元件 Devexpress使用之:GridControl控制元件

Devexpress使用之:GridControl控制元件

 

Devexpress系列控制元件功能很強大,使用起來也不太容易,我也是邊摸索邊使用,如果有時間我會把常用控制元件的使用方法整理出來的。

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraEditors.Repository;

namespace XtraGridDemo1
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
            
            //首先拖到窗體上一個GridControl,在表格上點選“Click here to change view”連結,在彈出選單中選擇“convert to”-->“AdvBandedGridView”。
            
            InitGrid();
        }

        ///初始化表格
        private void InitGrid()
        {

            // advBandedGridView1是表格上的預設檢視,注意這裡宣告的是:BandedGridView
            BandedGridView view = advBandedGridView1 as BandedGridView;
            
            view.BeginUpdate(); //開始檢視的編輯,防止觸發其他事件
            view.BeginDataUpdate(); //開始資料的編輯

            view.Bands.Clear();

            //修改附加選項
            view.OptionsView.ShowColumnHeaders = false;                         //因為有Band列了,所以把ColumnHeader隱藏
            view.OptionsView.ShowGroupPanel = false;                            //如果沒必要分組,就把它去掉
            view.OptionsView.EnableAppearanceEvenRow = false;                   //是否啟用偶數行外觀
            view.OptionsView.EnableAppearanceOddRow = true;                     //是否啟用奇數行外觀
            view.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;   //是否顯示過濾面板
            view.OptionsCustomization.AllowColumnMoving = false;                //是否允許移動列
            view.OptionsCustomization.AllowColumnResizing = false;              //是否允許調整列寬
            view.OptionsCustomization.AllowGroup = false;                       //是否允許分組
            view.OptionsCustomization.AllowFilter = false;                      //是否允許過濾
            view.OptionsCustomization.AllowSort = true;                         //是否允許排序
            view.OptionsSelection.EnableAppearanceFocusedCell = true;           //???
            view.OptionsBehavior.Editable = true;                               //是否允許使用者編輯單元格

            //新增列標題
            GridBand bandID = view.Bands.AddBand("ID");
            bandID.Visible = false; //隱藏ID列
            GridBand bandName = view.Bands.AddBand("姓名");
            GridBand bandSex = view.Bands.AddBand("性別");
            GridBand bandBirth = view.Bands.AddBand("出生日期");
            GridBand bandScore = view.Bands.AddBand("分數");
            GridBand bandMath = bandScore.Children.AddBand("數學");
            GridBand bandChinese = bandScore.Children.AddBand("語文");
            GridBand bandEnglish = bandScore.Children.AddBand("英語");
            GridBand bandSubTotal = bandScore.Children.AddBand("小計");
            GridBand bandRemark = view.Bands.AddBand("備註");

            //列標題對齊方式
            bandName.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandSex.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandBirth.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandScore.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandMath.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandChinese.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandEnglish.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandSubTotal.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            bandRemark.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;

            //模擬幾個資料
            List<Record> listDataSource = new List<Record>();
            listDataSource.Add(new Record(1, "張三","男",Convert.ToDateTime("1989-5-6") ,115.5f,101,96,""));
            listDataSource.Add(new Record(2, "李四", "女", Convert.ToDateTime("1987-12-23"), 92, 85, 87, ""));
            listDataSource.Add(new Record(3, "王五", "女", Convert.ToDateTime("1990-2-11"), 88, 69, 41.5f, ""));
            listDataSource.Add(new Record(4, "趙六", "男", Convert.ToDateTime("1988-9-1"), 119, 108, 110, "備註行"));
            //繫結資料來源並顯示
            gridControl1.DataSource = listDataSource;
            gridControl1.MainView.PopulateColumns();

            //[小計]這一列因為沒繫結資料來源,所以需要手動新增
            //(有點複雜,慢慢看吧)
            string[] fieldNames = new string[] { "SubTotal" };
            GridColumn column;   //宣告單列
            column = view.Columns.AddField(fieldNames[0]);  //新增一個數據欄位
            column.VisibleIndex = view.Columns.Count -1;  //設定該列在編輯檢視時的顯示位置(倒數第二列)  
            column.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            column.OptionsColumn.AllowEdit = false;     //此列不可編輯
            column.Visible = true;
            view.Columns.Add(column);   //檢視中新增一列

            //繫結事件,當[分數]改變時[小計]也跟著變
            //(好像只有在繫結事件裡才能改變該單元格數值,直接修改無效)
            view.CustomUnboundColumnData += new
                DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(advBandedGridView1_CustomUnboundColumnData);

            //[性別]列繫結ComboBox
            RepositoryItemComboBox riCombo = new RepositoryItemComboBox();
            riCombo.Items.AddRange(new string[] {"男", "女"});
            gridControl1.RepositoryItems.Add(riCombo);
            view.Columns["Sex"].ColumnEdit = riCombo;

            //[出生年月]列繫結Date
            RepositoryItemDateEdit riDate = new RepositoryItemDateEdit();
            gridControl1.RepositoryItems.Add(riDate);
            view.Columns["Birth"].ColumnEdit = riDate;

            //[分數]列繫結SpinEdit
            RepositoryItemSpinEdit riSpin = new RepositoryItemSpinEdit();
            gridControl1.RepositoryItems.Add(riSpin);
            view.Columns["Math"].ColumnEdit = riSpin;
            view.Columns["Chinese"].ColumnEdit = riSpin;
            view.Columns["English"].ColumnEdit = riSpin;

            //[備註]列繫結MemoExEdit
            RepositoryItemMemoExEdit riMemoEx = new RepositoryItemMemoExEdit();
            gridControl1.RepositoryItems.Add(riMemoEx);
            view.Columns["Remark"].ColumnEdit = riMemoEx;


            //小計列新增彙總
            view.OptionsView.ShowFooter = true;     //顯示錶格頁尾
            view.Columns["SubTotal"].SummaryItem.FieldName = "SubTotal";
            view.Columns["SubTotal"].SummaryItem.DisplayFormat = "{0:f2}";
            view.Columns["SubTotal"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Average;

            //將標題列和資料列對應
            view.Columns["ID"].OwnerBand = bandID;
            view.Columns["Name"].OwnerBand = bandName;
            view.Columns["Sex"].OwnerBand = bandSex;
            view.Columns["Birth"].OwnerBand = bandBirth;
            view.Columns["Math"].OwnerBand = bandMath;
            view.Columns["Chinese"].OwnerBand = bandChinese;
            view.Columns["English"].OwnerBand = bandEnglish;
            view.Columns["SubTotal"].OwnerBand = bandSubTotal;
            view.Columns["Remark"].OwnerBand = bandRemark;

            view.EndDataUpdate();//結束資料的編輯
            view.EndUpdate();   //結束檢視的編輯


        }



        // 計算小計
        private float calcSubTotal(float math, float chinese, float english)
        {
            return math + chinese + english;
        }


        private void advBandedGridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            ColumnView colView = sender as ColumnView;
            if (e.Column.FieldName == "SubTotal" && e.IsGetData) e.Value = calcSubTotal(
                     Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["Math"])),
                     Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["Chinese"])),
                     Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["English"])));
        }



        #region 執行時繫結到實現Ilist介面的資料來源

        public class Record
        {
            int id;
            DateTime birth;
            string name, sex, remark;
            float math, chinese, english;
            public Record(int id, string name, string sex, DateTime birth, float math, float chinese, float english, string remark)
            {
                this.id = id;
                this.name = name;
                this.sex = sex;
                this.birth = birth;
                this.math = math;
                this.chinese = chinese;
                this.english = english;
                this.remark = remark;
            }
            public int ID { get { return id; } }
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            public string Sex
            {
                get { return sex; }
                set { sex = value; }
            }
            public DateTime Birth
            {
                get { return birth; }
                set { birth = value; }
            }
            public float Math
            {
                get { return math; }
                set { math = value; }
            }
            public float Chinese
            {
                get { return chinese; }
                set { chinese = value; }
            }
            public float English
            {
                get { return english; }
                set { english = value; }
            }
            public string Remark
            {
                get { return remark; }
                set { remark = value; }
            }


        }

        #endregion


    }
}

  

  原文連結

 

http://www.cnblogs.com/habin/archive/2009/04/24/1442613.html