【C#】DevExpress實現複合表頭

陆陆无为而治者發表於2024-10-10

https://download.csdn.net/blog/column/9993043/120721622

①將建立的GridControl下的GirdView1轉化為BandGridView型別;

②建立需要展示的列(指定列的名稱【Name】、描述【caption】、資料欄位名稱【FieldName】)

③繫結列實現複合表頭。

注意:如果複合表頭有多行,則需要設定新增Band的Row Count,然後設定【Band properties下的AutoFillDown=false】

程式碼例子https://www.shuzhiduo.com/A/lk5aG060z1/

  1     using System;
  2     using System.Collections.Generic;
  3     using System.ComponentModel;
  4     using System.Windows.Forms;
  5     using DevExpress.XtraGrid.Columns;
  6     using DevExpress.XtraGrid.Views.Base;
  7     using DevExpress.XtraGrid.Views.BandedGrid;
  8     using DevExpress.XtraEditors.Repository;
  9      
 10     namespace XtraGridDemo1
 11     {
 12         public partial class Form1 : DevExpress.XtraEditors.XtraForm
 13         {
 14             public Form1()
 15             {
 16                 InitializeComponent();
 17                 
 18                 //首先拖到窗體上一個GridControl,在表格上點選“Click here to change view”連結,在彈出選單中選擇“convert to”-->“AdvBandedGridView”。
 19                 
 20                 InitGrid();
 21             }
 22      
 23             ///初始化表格
 24             private void InitGrid()
 25             {
 26      
 27                 // advBandedGridView1是表格上的預設檢視,注意這裡宣告的是:BandedGridView
 28                 BandedGridView view = advBandedGridView1 as BandedGridView;
 29                 
 30                 view.BeginUpdate(); //開始檢視的編輯,防止觸發其他事件
 31                 view.BeginDataUpdate(); //開始資料的編輯
 32      
 33                 view.Bands.Clear();
 34      
 35                 //修改附加選項
 36                 view.OptionsView.ShowColumnHeaders = false;                         //因為有Band列了,所以把ColumnHeader隱藏
 37                 view.OptionsView.ShowGroupPanel = false;                            //如果沒必要分組,就把它去掉
 38                 view.OptionsView.EnableAppearanceEvenRow = false;                   //是否啟用偶數行外觀
 39                 view.OptionsView.EnableAppearanceOddRow = true;                     //是否啟用奇數行外觀
 40                 view.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;   //是否顯示過濾皮膚
 41                 view.OptionsCustomization.AllowColumnMoving = false;                //是否允許移動列
 42                 view.OptionsCustomization.AllowColumnResizing = false;              //是否允許調整列寬
 43                 view.OptionsCustomization.AllowGroup = false;                       //是否允許分組
 44                 view.OptionsCustomization.AllowFilter = false;                      //是否允許過濾
 45                 view.OptionsCustomization.AllowSort = true;                         //是否允許排序
 46                 view.OptionsSelection.EnableAppearanceFocusedCell = true;           //???
 47                 view.OptionsBehavior.Editable = true;                               //是否允許使用者編輯單元格
 48      
 49                 //新增列標題
 50                 GridBand bandID = view.Bands.AddBand("ID");
 51                 bandID.Visible = false; //隱藏ID列
 52                 GridBand bandName = view.Bands.AddBand("姓名");
 53                 GridBand bandSex = view.Bands.AddBand("性別");
 54                 GridBand bandBirth = view.Bands.AddBand("出生日期");
 55                 GridBand bandScore = view.Bands.AddBand("分數");
 56                 GridBand bandMath = bandScore.Children.AddBand("數學");
 57                 GridBand bandChinese = bandScore.Children.AddBand("語文");
 58                 GridBand bandEnglish = bandScore.Children.AddBand("英語");
 59                 GridBand bandSubTotal = bandScore.Children.AddBand("小計");
 60                 GridBand bandRemark = view.Bands.AddBand("備註");
 61      
 62                 //列標題對齊方式
 63                 bandName.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 64                 bandSex.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 65                 bandBirth.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 66                 bandScore.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 67                 bandMath.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 68                 bandChinese.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 69                 bandEnglish.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 70                 bandSubTotal.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 71                 bandRemark.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
 72      
 73                 //模擬幾個資料
 74                 List<Record> listDataSource = new List<Record>();
 75                 listDataSource.Add(new Record(1, "張三","",Convert.ToDateTime("1989-5-6") ,115.5f,101,96,""));
 76                 listDataSource.Add(new Record(2, "李四", "", Convert.ToDateTime("1987-12-23"), 92, 85, 87, ""));
 77                 listDataSource.Add(new Record(3, "王五", "", Convert.ToDateTime("1990-2-11"), 88, 69, 41.5f, ""));
 78                 listDataSource.Add(new Record(4, "趙六", "", Convert.ToDateTime("1988-9-1"), 119, 108, 110, "備註行"));
 79                 //繫結資料來源並顯示
 80                 gridControl1.DataSource = listDataSource;
 81                 gridControl1.MainView.PopulateColumns();
 82             
 83                 //[小計]這一列因為沒繫結資料來源,所以需要手動新增
 84                 //(有點複雜,慢慢看吧)
 85                 string[] fieldNames = new string[] { "SubTotal" };
 86                 GridColumn column;   //宣告單列
 87                 column = view.Columns.AddField(fieldNames[0]);  //新增一個資料欄位
 88                 column.VisibleIndex = view.Columns.Count -1;  //設定該列在編輯檢視時的顯示位置(倒數第二列)  
 89                 column.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
 90                 column.OptionsColumn.AllowEdit = false;     //此列不可編輯
 91                 column.Visible = true;
 92                 view.Columns.Add(column);   //檢視中新增一列
 93      
 94                 //繫結事件,當[分數]改變時[小計]也跟著變
 95                 //(好像只有在繫結事件裡才能改變該單元格數值,直接修改無效)
 96                 view.CustomUnboundColumnData += new
 97                     DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(advBandedGridView1_CustomUnboundColumnData);
 98      
 99                 //[性別]列繫結ComboBox
100                 RepositoryItemComboBox riCombo = new RepositoryItemComboBox();
101                 riCombo.Items.AddRange(new string[] {"", ""});
102                 gridControl1.RepositoryItems.Add(riCombo);
103                 view.Columns["Sex"].ColumnEdit = riCombo;
104      
105                 //[出生年月]列繫結Date
106                 RepositoryItemDateEdit riDate = new RepositoryItemDateEdit();
107                 gridControl1.RepositoryItems.Add(riDate);
108                 view.Columns["Birth"].ColumnEdit = riDate;
109      
110                 //[分數]列繫結SpinEdit
111                 RepositoryItemSpinEdit riSpin = new RepositoryItemSpinEdit();
112                 gridControl1.RepositoryItems.Add(riSpin);
113                 view.Columns["Math"].ColumnEdit = riSpin;
114                 view.Columns["Chinese"].ColumnEdit = riSpin;
115                 view.Columns["English"].ColumnEdit = riSpin;
116      
117                 //[備註]列繫結MemoExEdit
118                 RepositoryItemMemoExEdit riMemoEx = new RepositoryItemMemoExEdit();
119                 gridControl1.RepositoryItems.Add(riMemoEx);
120                 view.Columns["Remark"].ColumnEdit = riMemoEx;
121      
122                 //小計列新增彙總
123                 view.OptionsView.ShowFooter = true;     //顯示錶格頁尾
124                 view.Columns["SubTotal"].SummaryItem.FieldName = "SubTotal";
125                 view.Columns["SubTotal"].SummaryItem.DisplayFormat = "{0:f2}";
126                 view.Columns["SubTotal"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Average;
127      
128                 //將標題列和資料列對應
129                 view.Columns["ID"].OwnerBand = bandID;
130                 view.Columns["Name"].OwnerBand = bandName;
131                 view.Columns["Sex"].OwnerBand = bandSex;
132                 view.Columns["Birth"].OwnerBand = bandBirth;
133                 view.Columns["Math"].OwnerBand = bandMath;
134                 view.Columns["Chinese"].OwnerBand = bandChinese;
135                 view.Columns["English"].OwnerBand = bandEnglish;
136                 view.Columns["SubTotal"].OwnerBand = bandSubTotal;
137                 view.Columns["Remark"].OwnerBand = bandRemark;
138      
139                 view.EndDataUpdate();//結束資料的編輯
140                 view.EndUpdate();   //結束檢視的編輯
141      
142             }
143      
144             // 計算小計
145             private float calcSubTotal(float math, float chinese, float english)
146             {
147                 return math + chinese + english;
148             }
149      
150             private void advBandedGridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
151             {
152                 ColumnView colView = sender as ColumnView;
153                 if (e.Column.FieldName == "SubTotal" && e.IsGetData) e.Value = calcSubTotal(
154                          Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["Math"])),
155                          Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["Chinese"])),
156                          Convert.ToSingle(colView.GetRowCellValue(e.RowHandle, colView.Columns["English"])));
157             }
158      
159             #region 執行時繫結到實現Ilist介面的資料來源
160      
161             public class Record
162             {
163                 int id;
164                 DateTime birth;
165                 string name, sex, remark;
166                 float math, chinese, english;
167                 public Record(int id, string name, string sex, DateTime birth, float math, float chinese, float english, string remark)
168                 {
169                     this.id = id;
170                     this.name = name;
171                     this.sex = sex;
172                     this.birth = birth;
173                     this.math = math;
174                     this.chinese = chinese;
175                     this.english = english;
176                     this.remark = remark;
177                 }
178                 public int ID { get { return id; } }
179                 public string Name
180                 {
181                     get { return name; }
182                     set { name = value; }
183                 }
184                 public string Sex
185                 {
186                     get { return sex; }
187                     set { sex = value; }
188                 }
189                 public DateTime Birth
190                 {
191                     get { return birth; }
192                     set { birth = value; }
193                 }
194                 public float Math
195                 {
196                     get { return math; }
197                     set { math = value; }
198                 }
199                 public float Chinese
200                 {
201                     get { return chinese; }
202                     set { chinese = value; }
203                 }
204                 public float English
205                 {
206                     get { return english; }
207                     set { english = value; }
208                 }
209                 public string Remark
210                 {
211                     get { return remark; }
212                     set { remark = value; }
213                 }
214      
215             }
216      
217             #endregion
218      
219         }
220     }

相關文章