剛到一家新公司,領(lǐng)導(dǎo)下發(fā)任務(wù)要用cs系統(tǒng)做一個(gè)表格折疊顯示,這真是把我難倒了,自己工作6年一直以來(lái)都是做BS的系統(tǒng)。這如果在BS里面那太簡(jiǎn)單了,JqGrid默認(rèn)都自帶,可是DataGridview不支持折疊啊。自己一點(diǎn)經(jīng)驗(yàn)沒(méi)有,怎么辦呢?于是上網(wǎng)搜了相關(guān)視頻,資料,開(kāi)始學(xué)習(xí)起來(lái)。最后借鑒源碼封了這么一個(gè)東西,發(fā)出來(lái)分享下,也能讓自己加深印象。
首先不多說(shuō),上圖。如果大家感謝還不錯(cuò),請(qǐng)繼續(xù)往下閱讀:
大概的效果就是這樣。
上代碼。
1、首先重寫(xiě)DataGridview,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
public class MasterControl : DataGridView { #region 字段 private List<int> rowCurrent = new List<int>(); internal static int rowDefaultHeight = ; internal static int rowExpandedHeight = ; internal static int rowDefaultDivider = ; internal static int rowExpandedDivider = - ; internal static int rowDividerMargin = ; internal static bool collapseRow; //detailControl變量作為一個(gè)容器用來(lái)保存子表格 public detailControl childView = new detailControl() { Visible = false }; // VBConversions Note: Initial value cannot be assigned here since it is non-static. Assignment has been moved to the class constructors. // internal System.Windows.Forms.ImageList RowHeaderIconList; private System.ComponentModel.Container components = null ; // DataSet _cDataset; string _foreignKey; string _primaryKey; string _filterFormat; private controlType EControlType; public int ExpandRowIndex = ; #endregion #region 構(gòu)造函數(shù) /// <summary> /// 通過(guò)傳遞過(guò)來(lái)的枚舉判斷是兩級(jí)還是三級(jí)展開(kāi),表的對(duì)應(yīng)關(guān)系通過(guò)Relations來(lái)讀取 /// 所以調(diào)用此構(gòu)造函數(shù)的時(shí)候必須要講Relations設(shè)置正確,才能正確顯示層級(jí)關(guān)系。 /// oDataSet.Relations.Add("", oDataSet.Tables["T"].Columns["Menu_ID"], oDataSet.Tables["T"].Columns["Menu_ID"]); /// oDataSet.Relations.Add("", oDataSet.Tables["T"].Columns["Menu_Name"], oDataSet.Tables["T"].Columns["Menu_Name"]); /// 這兩次Add的順序不能顛倒,必須先添加一、二級(jí)的表關(guān)聯(lián),再添加二、三級(jí)的表關(guān)聯(lián) /// </summary> /// <param name="cDataset">數(shù)據(jù)源DataSet,里面還有各個(gè)表的對(duì)應(yīng)關(guān)系</param> /// <param name="eControlType">枚舉類(lèi)型</param> public MasterControl(DataSet cDataset, controlType eControlType) { SetMasterControl(cDataset, eControlType); } /// <summary> /// 第二種使用方法 /// </summary> /// <param name="lstData">折疊控件第一層的集合</param> /// <param name="lstData">折疊控件第二層的集合</param> /// <param name="lstData">折疊控件第三層的集合</param> /// <param name="dicRelateKey">第一二層之間對(duì)應(yīng)主外鍵</param> /// <param name="dicRelateKey">第二三層之間對(duì)應(yīng)主外鍵</param> /// <param name="eControlType">枚舉類(lèi)型</param> public MasterControl(object lstData, object lstData, object lstData, Dictionary<string, string> dicRelateKey, Dictionary<string ,string>dicRelateKey, controlType eControlType) { var oDataSet = new DataSet(); try { var oTable = new DataTable(); oTable = Fill(lstData); oTable.TableName = "T" ; var oTable = Fill(lstData); oTable.TableName = "T" ; if (lstData == null || dicRelateKey == null || dicRelateKey.Keys.Count <= ) { oDataSet.Tables.AddRange( new DataTable[] { oTable, oTable }); oDataSet.Relations.Add( "" , oDataSet.Tables[ "T" ].Columns[dicRelateKey.Keys.FirstOrDefault()], oDataSet.Tables[ "T" ].Columns[dicRelateKey.Values.FirstOrDefault()]); } else { var oTable = Fill(lstData); oTable.TableName = "T" ; oDataSet.Tables.AddRange( new DataTable[] { oTable, oTable, oTable }); //這是對(duì)應(yīng)關(guān)系的時(shí)候主鍵必須唯一 oDataSet.Relations.Add( "" , oDataSet.Tables[ "T" ].Columns[dicRelateKey.Keys.FirstOrDefault()], oDataSet.Tables[ "T" ].Columns[dicRelateKey.Values.FirstOrDefault()]); oDataSet.Relations.Add( "" , oDataSet.Tables[ "T" ].Columns[dicRelateKey.Keys.FirstOrDefault()], oDataSet.Tables[ "T" ].Columns[dicRelateKey.Values.FirstOrDefault()]); } } catch { oDataSet = new DataSet(); } SetMasterControl(oDataSet, eControlType); } /// <summary> /// 控件初始化 /// </summary> private void InitializeComponent() { this .components = new System.ComponentModel.Container(); base.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(MasterControl_RowHeaderMouseClick); base.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(MasterControl_RowPostPaint); base.Scroll += new System.Windows.Forms.ScrollEventHandler(MasterControl_Scroll); base.SelectionChanged += new System.EventHandler(MasterControl_SelectionChanged); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof (MasterControl)); this .RowHeaderIconList = new System.Windows.Forms.ImageList( this .components); ((System.ComponentModel.ISupportInitialize) this ).BeginInit(); this .SuspendLayout(); // //RowHeaderIconList // this .RowHeaderIconList.ImageStream = (System.Windows.Forms.ImageListStreamer)(resources.GetObject( "RowHeaderIconList.ImageStream" )); this .RowHeaderIconList.TransparentColor = System.Drawing.Color.Transparent; this .RowHeaderIconList.Images.SetKeyName(, "expand.png" ); this .RowHeaderIconList.Images.SetKeyName(, "collapse.png" ); // //MasterControl // ((System.ComponentModel.ISupportInitialize) this ).EndInit(); this .ResumeLayout( false ); } #endregion #region 數(shù)據(jù)綁定 /// <summary> /// 設(shè)置表之間的主外鍵關(guān)聯(lián) /// </summary> /// <param name="tableName">DataTable的表名稱(chēng)</param> /// <param name="foreignKey">外鍵</param> public void setParentSource(string tableName, string primarykey, string foreignKey) { this .DataSource = new DataView(_cDataset.Tables[tableName]); cModule.setGridRowHeader( this ); _foreignKey = foreignKey; _primaryKey = primarykey; if (_cDataset.Tables[tableName].Columns[primarykey].GetType().ToString() == typeof (int).ToString() || _cDataset.Tables[tableName].Columns[primarykey].GetType().ToString() == typeof (double).ToString() || _cDataset.Tables[tableName].Columns[primarykey].GetType().ToString() == typeof (decimal).ToString()) { _filterFormat = foreignKey + "={}" ; } else { _filterFormat = foreignKey + "=\'{}\'" ; } } #endregion #region 事件 //控件的行頭點(diǎn)擊事件 private void MasterControl_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { try { Rectangle rect = new Rectangle(System.Convert.ToInt((double)(rowDefaultHeight - ) / ), System.Convert.ToInt((double)(rowDefaultHeight - ) / ), , ); if (rect.Contains(e.Location)) { //縮起 if (rowCurrent.Contains(e.RowIndex)) { rowCurrent.Clear(); this .Rows[e.RowIndex].Height = rowDefaultHeight; this .Rows[e.RowIndex].DividerHeight = rowDefaultDivider; this .ClearSelection(); collapseRow = true ; this .Rows[e.RowIndex].Selected = true ; if (EControlType == controlType.middle) { var oParent = ((MasterControl) this .Parent.Parent); oParent.Rows[oParent.ExpandRowIndex].Height = rowDefaultHeight * ( this .Rows.Count + ); oParent.Rows[oParent.ExpandRowIndex].DividerHeight = rowDefaultHeight * ( this .Rows.Count + ); if (oParent.Rows[oParent.ExpandRowIndex].Height > ) { oParent.Rows[oParent.ExpandRowIndex].Height = ; oParent.Rows[oParent.ExpandRowIndex].Height = ; } } } //展開(kāi) else { if (!(rowCurrent.Count == )) { var eRow = rowCurrent[]; rowCurrent.Clear(); this .Rows[eRow].Height = rowDefaultHeight; this .Rows[eRow].DividerHeight = rowDefaultDivider; this .ClearSelection(); collapseRow = true ; this .Rows[eRow].Selected = true ; } rowCurrent.Add(e.RowIndex); this .ClearSelection(); collapseRow = true ; this .Rows[e.RowIndex].Selected = true ; this .ExpandRowIndex = e.RowIndex; this .Rows[e.RowIndex].Height = + rowDefaultHeight * (((DataView)(childView.childGrid[].DataSource)).Count + ); this .Rows[e.RowIndex].DividerHeight = + rowDefaultHeight * (((DataView)(childView.childGrid[].DataSource)).Count); //設(shè)置一個(gè)最大高度 if ( this .Rows[e.RowIndex].Height > ) { this .Rows[e.RowIndex].Height = ; this .Rows[e.RowIndex].DividerHeight = ; } if (EControlType == controlType.middle) { if ( this .Parent.Parent.GetType() != typeof (MasterControl)) return ; var oParent = ((MasterControl) this .Parent.Parent); oParent.Rows[oParent.ExpandRowIndex].Height = this .Rows[e.RowIndex].Height + rowDefaultHeight * ( this .Rows.Count + ); oParent.Rows[oParent.ExpandRowIndex].DividerHeight = this .Rows[e.RowIndex].DividerHeight + rowDefaultHeight * ( this .Rows.Count + ); if (oParent.Rows[oParent.ExpandRowIndex].Height > ) { oParent.Rows[oParent.ExpandRowIndex].Height = ; oParent.Rows[oParent.ExpandRowIndex].Height = ; } } //if (EControlType == controlType.outside) //{ // //SetControl(this); //} //this.Rows[e.RowIndex].Height = rowExpandedHeight; //this.Rows[e.RowIndex].DividerHeight = rowExpandedDivider; } //this.ClearSelection(); //collapseRow = true; //this.Rows[e.RowIndex].Selected = true; } else { collapseRow = false ; } } catch (Exception ex) { } } //控件的行重繪事件 private void MasterControl_RowPostPaint(object obj_sender, DataGridViewRowPostPaintEventArgs e) { try { var sender = (DataGridView)obj_sender; //set childview control var rect = new Rectangle((int)(e.RowBounds.X + ((double)(rowDefaultHeight - ) / )), (int)(e.RowBounds.Y + ((double)(rowDefaultHeight - ) / )), , ); if (collapseRow) { if ( this .rowCurrent.Contains(e.RowIndex)) { #region 更改點(diǎn)開(kāi)后背景色 劉金龍 var rect = new Rectangle(e.RowBounds.X, e.RowBounds.Y + rowDefaultHeight, e.RowBounds.Width, e.RowBounds.Height - rowDefaultHeight); using (Brush b = new SolidBrush(Color.FromArgb(, , ))) { e.Graphics.FillRectangle(b, rect); } #endregion sender.Rows[e.RowIndex].DividerHeight = sender.Rows[e.RowIndex].Height - rowDefaultHeight; e.Graphics.DrawImage(RowHeaderIconList.Images[(int)rowHeaderIcons.collapse], rect); childView.Location = new Point(e.RowBounds.Left + sender.RowHeadersWidth, e.RowBounds.Top + rowDefaultHeight + ); childView.Width = e.RowBounds.Right - sender.RowHeadersWidth; childView.Height = System.Convert.ToInt(sender.Rows[e.RowIndex].DividerHeight - ); childView.Visible = true ; } else { childView.Visible = false ; e.Graphics.DrawImage(RowHeaderIconList.Images[(int)rowHeaderIcons.expand], rect); } collapseRow = false ; } else { if ( this .rowCurrent.Contains(e.RowIndex)) { #region 更改點(diǎn)開(kāi)后背景色 劉金龍 var rect = new Rectangle(e.RowBounds.X, e.RowBounds.Y + rowDefaultHeight, e.RowBounds.Width, e.RowBounds.Height - rowDefaultHeight); using (Brush b = new SolidBrush(Color.FromArgb(,,))) { e.Graphics.FillRectangle(b, rect); } #endregion sender.Rows[e.RowIndex].DividerHeight = sender.Rows[e.RowIndex].Height - rowDefaultHeight; e.Graphics.DrawImage(RowHeaderIconList.Images[(int)rowHeaderIcons.collapse], rect); childView.Location = new Point(e.RowBounds.Left + sender.RowHeadersWidth, e.RowBounds.Top + rowDefaultHeight + ); childView.Width = e.RowBounds.Right - sender.RowHeadersWidth; childView.Height = System.Convert.ToInt(sender.Rows[e.RowIndex].DividerHeight - ); childView.Visible = true ; } else { childView.Visible = false ; e.Graphics.DrawImage(RowHeaderIconList.Images[(int)rowHeaderIcons.expand], rect); } } cModule.rowPostPaint_HeaderCount(sender, e); } catch { } } //控件的滾動(dòng)條滾動(dòng)事件 private void MasterControl_Scroll(object sender, ScrollEventArgs e) { try { if (!(rowCurrent.Count == )) { collapseRow = true ; this .ClearSelection(); this .Rows[rowCurrent[]].Selected = true ; } } catch { } } //控件的單元格選擇事件 private void MasterControl_SelectionChanged(object sender, EventArgs e) { try { if (!( this .RowCount == )) { if (rowCurrent.Contains( this .CurrentRow.Index)) { foreach (DataGridView cGrid in childView.childGrid) { ((DataView)cGrid.DataSource).RowFilter = string.Format(_filterFormat, this [_primaryKey, this .CurrentRow.Index].Value); } } } } catch { } } #endregion #region Private //設(shè)置構(gòu)造函數(shù)的參數(shù) private void SetMasterControl(DataSet cDataset, controlType eControlType) { //.控件初始化賦值 this .Controls.Add(childView); InitializeComponent(); _cDataset = cDataset; childView._cDataset = cDataset; cModule.applyGridTheme( this ); Dock = DockStyle.Fill; EControlType = eControlType; this .AllowUserToAddRows = false ; //.通過(guò)讀取DataSet里面的Relations得到表的關(guān)聯(lián)關(guān)系 if (cDataset.Relations.Count <= ) { return ; } DataRelation oRelates; if (eControlType == controlType.outside) { oRelates = cDataset.Relations[]; childView.Add(oRelates.ParentTable.TableName, oRelates.ParentColumns[].ColumnName, oRelates.ChildColumns[].ColumnName); } else if (eControlType == controlType.middle) { oRelates = cDataset.Relations[cDataset.Relations.Count - ]; childView.Add(oRelates.ChildTable.TableName); } //.設(shè)置主外鍵對(duì)應(yīng)關(guān)系 oRelates = cDataset.Relations[]; //主表里面的值,副表里面的過(guò)濾字段 setParentSource(oRelates.ParentTable.TableName,oRelates.ParentColumns[].ColumnName, oRelates.ChildColumns[].ColumnName); } private void SetControl(MasterControl oGrid) { oGrid.childView.RemoveControl(); //oGrid.childView.Controls.RemoveByKey("ChildrenMaster"); // //var oRelates = _cDataset.Relations[]; //oGrid.childView.Add(oRelates.ParentTable.TableName, oRelates.ChildColumns[].ColumnName); //foreach (var oGridControl in oGrid.Controls) //{ // if (oGridControl.GetType() != typeof(detailControl)) // { // continue; // } // var DetailControl =(detailControl)oGridControl; // foreach (var odetailControl in DetailControl.Controls) // { // if (odetailControl.GetType() != typeof(MasterControl)) // { // continue; // } // var OMasterControl = (MasterControl)odetailControl; // foreach (var oMasterControl in OMasterControl.Controls) // { // if (oMasterControl.GetType() == typeof(detailControl)) // { // ((detailControl)oMasterControl).Visible = false; // return; // } // } // } //} } //將List集合轉(zhuǎn)換成DataTable private DataTable Fill(object obj) { if (!(obj is IList)) { return null ; } var objlist = obj as IList; if (objlist == null || objlist.Count <= ) { return null ; } var tType = objlist[]; DataTable dt = new DataTable(tType.GetType().Name); DataColumn column; DataRow row; System.Reflection.PropertyInfo[] myPropertyInfo = tType.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach ( var t in objlist) { if (t == null ) { continue ; } row = dt.NewRow(); for (int i = , j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null ) { column = new DataColumn(name, pi.PropertyType); dt.Columns.Add(column); } row[name] = pi.GetValue(t, null ); } dt.Rows.Add(row); } return dt; } #endregion } |
2、detailControl變量作為一個(gè)容器用來(lái)保存子表格
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
public class detailControl : Ewin.Client.Frame.Controls.EwinPanel { #region 字段 public List<DataGridView> childGrid = new List<DataGridView>(); public DataSet _cDataset; #endregion #region 方法 public void Add( string tableName, string strPrimaryKey, string strForeignKey) { //TabPage tPage = new TabPage() { Text = pageCaption }; //this.Controls.Add(tPage); var newGrid = new MasterControl(_cDataset, controlType.middle) { Dock = DockStyle.Fill, DataSource = new DataView(_cDataset.Tables[tableName]) }; newGrid.setParentSource(tableName, strPrimaryKey, strForeignKey); //設(shè)置主外鍵 //newGrid.Name = "ChildrenMaster"; //tPage.Controls.Add(newGrid); this .Controls.Add(newGrid); //this.BorderStyle = BorderStyle.FixedSingle; cModule.applyGridTheme(newGrid); cModule.setGridRowHeader(newGrid); newGrid.RowPostPaint += cModule.rowPostPaint_HeaderCount; childGrid.Add(newGrid); } public void Add( string tableName) { //TabPage tPage = new TabPage() { Text = pageCaption }; //this.Controls.Add(tPage); DataGridView newGrid = new Ewin.Client.Frame.Controls.EwinGrid() { Dock = DockStyle.Fill, DataSource = new DataView(_cDataset.Tables[tableName]) }; newGrid.AllowUserToAddRows = false ; //tPage.Controls.Add(newGrid); this .Controls.Add(newGrid); cModule.applyGridTheme(newGrid); cModule.setGridRowHeader(newGrid); newGrid.RowPostPaint += cModule.rowPostPaint_HeaderCount; childGrid.Add(newGrid); } public void RemoveControl() { this .Controls.Remove(childGrid[]); childGrid.Clear(); } #endregion } |
3、cModule.cs用來(lái)設(shè)置樣式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
namespace Ewin.Client.Frame.UcGrid { /// <summary> /// 折疊控件樣式以及行數(shù)操作類(lèi) /// </summary> sealed class cModule { #region CustomGrid static System.Windows.Forms.DataGridViewCellStyle dateCellStyle = new System.Windows.Forms.DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleRight }; static System.Windows.Forms.DataGridViewCellStyle amountCellStyle = new System.Windows.Forms.DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleRight, Format = "N" }; static System.Windows.Forms.DataGridViewCellStyle gridCellStyle = new System.Windows.Forms.DataGridViewCellStyle { Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft, BackColor = System.Drawing.Color.FromArgb(System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte())), Font = new System.Drawing.Font( "Segoe UI" , ( float )(.F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte()), ForeColor = System.Drawing.SystemColors.ControlLightLight, SelectionBackColor = System.Drawing.SystemColors.Highlight, SelectionForeColor = System.Drawing.SystemColors.HighlightText, WrapMode = System.Windows.Forms.DataGridViewTriState.True }; static System.Windows.Forms.DataGridViewCellStyle gridCellStyle = new System.Windows.Forms.DataGridViewCellStyle { Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft, BackColor = System.Drawing.SystemColors.ControlLightLight, Font = new System.Drawing.Font( "Segoe UI" , ( float )(.F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte()), ForeColor = System.Drawing.SystemColors.ControlText, SelectionBackColor = System.Drawing.Color.FromArgb(System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte())), SelectionForeColor = System.Drawing.SystemColors.HighlightText, WrapMode = System.Windows.Forms.DataGridViewTriState.False }; static System.Windows.Forms.DataGridViewCellStyle gridCellStyle = new System.Windows.Forms.DataGridViewCellStyle { Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft, BackColor = System.Drawing.Color.WhiteSmoke, Font = new System.Drawing.Font( "Segoe UI" , ( float )(.F), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte()), ForeColor = System.Drawing.SystemColors.WindowText, SelectionBackColor = System.Drawing.Color.FromArgb(System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte()), System.Convert.ToInt(System.Convert.ToByte())), SelectionForeColor = System.Drawing.SystemColors.HighlightText, WrapMode = System.Windows.Forms.DataGridViewTriState.True }; //設(shè)置表格的主題樣式 static public void applyGridTheme(DataGridView grid) { grid.AllowUserToAddRows = false ; grid.AllowUserToDeleteRows = false ; grid.BackgroundColor = System.Drawing.SystemColors.Window; grid.BorderStyle = System.Windows.Forms.BorderStyle.None; grid.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; grid.ColumnHeadersDefaultCellStyle = gridCellStyle; grid.ColumnHeadersHeight = ; grid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; grid.DefaultCellStyle = gridCellStyle; grid.EnableHeadersVisualStyles = false ; grid.GridColor = System.Drawing.SystemColors.GradientInactiveCaption; //grid.ReadOnly = true; grid.RowHeadersVisible = true ; grid.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; grid.RowHeadersDefaultCellStyle = gridCellStyle; grid.Font = gridCellStyle.Font; } //設(shè)置表格單元格樣式 static public void setGridRowHeader(DataGridView dgv, bool hSize = false ) { dgv.TopLeftHeaderCell.Value = "NO " ; dgv.TopLeftHeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders); foreach (DataGridViewColumn cCol in dgv.Columns) { if (cCol.ValueType.ToString() == typeof (DateTime).ToString()) { cCol.DefaultCellStyle = dateCellStyle; } else if (cCol.ValueType.ToString() == typeof ( decimal ).ToString() || cCol.ValueType.ToString() == typeof ( double ).ToString()) { cCol.DefaultCellStyle = amountCellStyle; } } if (hSize) { dgv.RowHeadersWidth = dgv.RowHeadersWidth + ; } dgv.AutoResizeColumns(); } //設(shè)置表格的行號(hào) static public void rowPostPaint_HeaderCount( object obj_sender, DataGridViewRowPostPaintEventArgs e) { try { var sender = (DataGridView)obj_sender; //set rowheader count DataGridView grid = (DataGridView)sender; string rowIdx = System.Convert.ToString((e.RowIndex + ).ToString()); var centerFormat = new StringFormat(); centerFormat.Alignment = StringAlignment.Center; centerFormat.LineAlignment = StringAlignment.Center; Rectangle headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height - sender.Rows[e.RowIndex].DividerHeight); e.Graphics.DrawString(rowIdx, grid.Font, SystemBrushes.ControlText, headerBounds, centerFormat); } catch (Exception ex) { } } #endregion } /// <summary> /// 控件類(lèi)型,是最外層的表格還是中間層的表格 /// </summary> public enum controlType { outside = , middle = } /// <summary> /// 展開(kāi)圖標(biāo) /// </summary> public enum rowHeaderIcons { expand = , collapse = } } |
4、From頁(yè)面調(diào)用
#region 使用方法一
1
2
3
4
|
//var oDataSet = GetDataSet(); // //masterDetail = new MasterControl(oDataSet, controlType.outside); #endregion |
#region 使用方法二
1
2
3
4
5
|
var dicRelateData1 = new Dictionary< string , string >(); var dicRelateData2 = new Dictionary< string , string >(); dicRelateData1.Add( "Menu_ID" , "Menu_ID" ); //表格一和表格二之間的主外鍵關(guān)系 dicRelateData2.Add( "Menu_Name2" , "Menu_Name2" ); //表格二和表格三之間的主外鍵關(guān)系 masterDetail = new MasterControl(GetDataSource(), GetDataSource2(), GetDataSource3(), dicRelateData1, dicRelateData2, controlType.outside); #endregion panelView.Controls.Add(masterDetail); |
昨天應(yīng)領(lǐng)導(dǎo)要求,折疊控件增加了折疊線的效果,看起來(lái)有沒(méi)有更加像模像樣了。~~~
其實(shí)就在行重繪事件private void MasterControl_RowPostPaint(object obj_sender, DataGridViewRowPostPaintEventArgs e)里面增加了如下代碼:
1
2
3
4
5
6
7
8
9
|
using (Pen p = new Pen(Color.GhostWhite)) { var iHalfWidth = (e.RowBounds.Left + sender.RowHeadersWidth) / 2; var oPointHLineStart = new Point(rect1.X + iHalfWidth, rect1.Y); var oPointHLineEnd = new Point(rect1.X + iHalfWidth, rect1.Y + rect1.Height / 2); e.Graphics.DrawLine(p, oPointHLineStart, oPointHLineEnd); //折疊線 e.Graphics.DrawLine(p, oPointHLineEnd, new Point(oPointHLineEnd.X + iHalfWidth, oPointHLineEnd.Y)); } |
效果如下:
以上所述是小編給大家介紹的WinForm中DataGridView折疊控件的相關(guān)知識(shí),希望對(duì)大家有所幫助!