winform DataGridView-----2

  上一篇对Data'gridView做了简单的封装,基本能满足正常开发了,后来我发现一个单元中同时会又左边图标右边文字的情况,这次就把这个也加上。所以我自定义歌一个组件。

  自定义  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
public partial class GridList : DataGridView
   {
       private Dictionary<int, Image> dic { get; set; }
 
       public void SetHeader(List<dataGridViewModel> viewModel)
       {
           dic = new Dictionary<int, Image>();
           this.CellFormatting += Grid_cellFormartting;
           foreach (var item in viewModel)
           {
               switch (item.colType)
               {
                   case ColType.文本:
                       this.AutoGenerateColumns = false;
                       TextAndImageColumn ColumnRoleID = new TextAndImageColumn();
                       ColumnRoleID.DataPropertyName = item.colName;
                       ColumnRoleID.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                       ColumnRoleID.Name = item.colName;
                       ColumnRoleID.HeaderText = item.colTitle;
                       this.Columns.Add(ColumnRoleID);
                       break;
                   case ColType.图标://单独一列显示图标
                       this.SetImage();
                       break;
                   case ColType.图标文本://单独一列显示图标
                       SetCellImgOrText(item.cell);
                       break;
                   case ColType.按钮:
                       this.SetButton(item.TitleData);
                       break;
                   default:
                       break;
               }
           }
       }
       /// <summary>
       /// 设置图标文字
       /// </summary>
       /// <param name="cellType"></param>
        private void SetCellImgOrText(CellType cellType)
        {
           dic.Add(cellType.ColIndex, cellType.ImageType);
        }
         
       /// <summary>
       /// 列表添加图片
       /// </summary>
       private  void SetImage()
       {
           DataGridViewImageColumn Imange = new DataGridViewImageColumn();
           Imange.ImageLayout = DataGridViewImageCellLayout.Zoom;
           // Imange.HeaderText = "图标";
           this.Columns.Add(Imange);
       }
       /// <summary>
       /// 列表添加操作按钮
       /// </summary>
       /// <param name="gridView"></param>
       public  void SetButton( Title title)
       {
           if (title == null)
           {
               return;
           }
           DataGridViewButtonColumn select = new DataGridViewButtonColumn
           {
               Name = title.headTitle,
               Text = title.Text,
               UseColumnTextForButtonValue = true,
               DataPropertyName = "operate",
               FillWeight = 5,
               HeaderText = title.headText
           };
           select.FlatStyle = FlatStyle.Flat;
           select.Width = 20;
           select.DefaultCellStyle.ForeColor = string.IsNullOrEmpty(title.color) ? Color.Black : colorHx16toRGB(title.color);
           this.Columns.Add(select);
       }
       /// <summary>
       /// 设置隐藏某一列
       /// </summary>
       /// <param name="gridView"></param>
       /// <param name="colVisible"></param>
       public  void SetColVisible( string[] colVisible)
       {
           for (int i = 0; i < colVisible.Length; i++)
           {
               this.Columns[colVisible[i]].Visible = false;
           }
 
       }
       /// <summary>
       /// 对某些列进行列宽设置
       /// </summary>
       /// <param name="gridView"></param>
       /// <param name="colWidth"></param>
       public  void SetColWidth(Dictionary<int, int> colWidth)
       {
           foreach (int key in colWidth.Keys)
           {
               this.Columns[key].Width = colWidth[key];
           }
       }
       /// <summary>
       /// 表头颜色设置
       /// </summary>
       public  void SetHeadColor( string color)
       {
           //设置行表头的颜色
           this.EnableHeadersVisualStyles = false;
           this.ColumnHeadersDefaultCellStyle.BackColor = colorHx16toRGB(color);
 
       }
       /// <summary>
       /// 表头颜色设置
       /// </summary>
       public  void SetHeadColor(int R, int G, int B)
       {
           //设置行表头的颜色
           this.EnableHeadersVisualStyles = false;
           this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(R, G, B);
 
       }
       
       /// <summary>
       /// 设置表头文字颜色
       /// </summary>
 
       public  void SetHeadFontColor( int R, int G, int B)
       {
           //表头文字颜色
           this.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(R, G, B);
       }
       /// <summary>
       /// 设置文字类型
       /// </summary>
       /// <param name="gridView"></param>
       /// <param name="fontType"></param>
       public  void SetHeadFontType( Font fontType)
       {
           //行表头文字类型
           this.ColumnHeadersDefaultCellStyle.Font = fontType;
       }
       /// <summary>
       /// 设置表头行高0
       /// </summary>
       /// <param name="gridView"></param>
       /// <param name="rowHeight"></param>
       public void SetHeadRowHeight( int rowHeight)
       {
           //改变标题的行高
           this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
           this.ColumnHeadersHeight = rowHeight;
       }
       /// <summary>
       /// 居中标题
       /// </summary>
       public void SetHeadCenter()
       {
           this.AutoSize = false;
           //标题居中
          this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
       }
       /// <summary>
       /// 去除第一列空列
       /// </summary>
       public void SetRowHeadersVisible()
       {
           this.RowHeadersVisible = false;
 
       }
       /// <summary>
       /// 去除最后一行空行
       /// </summary>
       public  void SetAllowUserToAddRows()
       {
           this.AllowUserToAddRows = false;
       }
       public  void SetCellRowFull()
       {
           this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
       }
       public GridList()
       {
           InitializeComponent();
            
       }
 
       private void Grid_cellFormartting(object sender, DataGridViewCellFormattingEventArgs e)
       {
           foreach (int key in dic.Keys)
           {
               if (e.ColumnIndex==key)
               {
                   TextAndImageCell cell = this.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
                   if (cell != null && e.Value != null)
                   {
                       try
                       {
 
                           cell.Image = dic[key];
                       }
                       catch (Exception ex)
                       {
 
                       }
                   }
               }
           }
           
       }
 
       public GridList(IContainer container)
       {
           container.Add(this);
 
           InitializeComponent();
       }
       public Color colorHx16toRGB(string strHxColor)
       {
           try
           {
               if (strHxColor.Length == 0)
               {//如果为空
                   return Color.FromArgb(0, 0, 0);//设为黑色
               }
               else
               {//转换颜色
                   return Color.FromArgb(System.Int32.Parse(strHxColor.Substring(1, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(3, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(5, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
               }
           }
           catch
           {//设为黑色
               return Color.FromArgb(0, 0, 0);
           }
       }
   }
 
   public class TextAndImageColumn : DataGridViewTextBoxColumn
   {
       private Image imageValue;
       private Size imageSize;
 
       public TextAndImageColumn()
       {
           this.CellTemplate = new TextAndImageCell();
       }
 
       public override object Clone()
       {
           TextAndImageColumn c = base.Clone() as TextAndImageColumn;
           c.imageValue = this.imageValue;
           c.imageSize = this.imageSize;
           return c;
       }
 
       public Image Image
       {
           get { return this.imageValue; }
           set
           {
               if (this.Image != value)
               {
                   this.imageValue = value;
                   this.imageSize = value.Size;
 
                   if (this.InheritedStyle != null)
                   {
                       Padding inheritedPadding = this.InheritedStyle.Padding;
                       this.DefaultCellStyle.Padding = new Padding(imageSize.Width,
                   inheritedPadding.Top, inheritedPadding.Right,
                   inheritedPadding.Bottom);
                   }
               }
           }
       }
       private TextAndImageCell TextAndImageCellTemplate
       {
           get { return this.CellTemplate as TextAndImageCell; }
       }
       internal Size ImageSize
       {
           get { return imageSize; }
       }
   }
 
   public class TextAndImageCell : DataGridViewTextBoxCell
   {
       private Image imageValue;
       private Size imageSize;
 
       public override object Clone()
       {
           TextAndImageCell c = base.Clone() as TextAndImageCell;
           c.imageValue = this.imageValue;
           c.imageSize = this.imageSize;
           return c;
       }
 
       public Image Image
       {
           get
           {
               if (this.OwningColumn == null ||
          this.OwningTextAndImageColumn == null)
               {
 
                   return imageValue;
               }
               else if (this.imageValue != null)
               {
                   return this.imageValue;
               }
               else
               {
                   return this.OwningTextAndImageColumn.Image;
               }
           }
           set
           {
               if (this.imageValue != value)
               {
                   this.imageValue = value;
                   this.imageSize = value.Size;
 
                   Padding inheritedPadding = this.InheritedStyle.Padding;
                   this.Style.Padding = new Padding(imageSize.Width,
                  inheritedPadding.Top, inheritedPadding.Right,
                  inheritedPadding.Bottom);
               }
           }
       }
       protected override void Paint(Graphics graphics, Rectangle clipBounds,
      Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
      object value, object formattedValue, string errorText,
      DataGridViewCellStyle cellStyle,
      DataGridViewAdvancedBorderStyle advancedBorderStyle,
      DataGridViewPaintParts paintParts)
       {
           // Paint the base content
           base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
             value, formattedValue, errorText, cellStyle,
             advancedBorderStyle, paintParts);
 
           if (this.Image != null)
           {
               // Draw the image clipped to the cell.
               System.Drawing.Drawing2D.GraphicsContainer container =
              graphics.BeginContainer();
 
               graphics.SetClip(cellBounds);
               graphics.DrawImageUnscaled(this.Image, cellBounds.Location);
 
               graphics.EndContainer(container);
           }
       }
 
       private TextAndImageColumn OwningTextAndImageColumn
       {
           get { return this.OwningColumn as TextAndImageColumn; }
       }
   }

  Model:

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
public enum ColType
   {
       文本,
       图标,
       图标文本,
       按钮
   }
  
   public class dataGridViewModel
   {
       public string colName { get; set; }
       public string colTitle { get; set; }
       public ColType colType { get; set; }
       public Title TitleData { get; set; }
       public CellType cell { get; set; }
 
   }
   /// <summary>
   /// 图标,文字
   /// </summary>
   public class CellType
   {
       public int ColIndex { get; set; }
       public Image ImageType { get; set; }
 
   }
   /// <summary>
   /// 按钮
   /// </summary>
   public class Title
   {
       public string headTitle { get; set; }
       public string Text { get; set; }
       public string headText { get; set; }
       public string color { get; set; }
   }

  实现:

从心编译工程,工具箱中会出现自定义控件:

 

 

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
//设置行表头的颜色
            //dataGridView_Mark.SetHeadColor("#F5F5F5");
            gridList1.SetHeadColor(250, 250, 250);
            //表头文字颜色
            //  dataGridView_File2.SetHeadFontColor("#F5F5F5");
            gridList1.SetHeadFontColor(95, 95, 95);
            //行表头文字类型
            gridList1.SetHeadFontType(new Font("楷体", 8, FontStyle.Bold));
            //改变标题的行高
            gridList1.SetHeadRowHeight(30);
            //去除第一列空列
            gridList1.SetRowHeadersVisible();
            //行占满
            gridList1.SetCellRowFull();
            //去除最后一行空行
            gridList1.SetAllowUserToAddRows();
            //标题居中
            gridList1.SetHeadCenter();
            List<dataGridViewModel> viewModel = new List<dataGridViewModel>()
            {
                new dataGridViewModel(){colType=ColType.图标},
 
                new dataGridViewModel(){colName="title",colTitle="标题",colType=ColType.图标文本,cell= new CellType(){ColIndex=2,ImageType=Properties.Resources.excel } },
                new dataGridViewModel(){colName="title1",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title2",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title3",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title4",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title5",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){ colType = ColType.按钮,TitleData=new Title(){ headTitle="btnfile4",Text="按钮",headText="操作" } },
            };
            gridList1.SetHeader(viewModel);
            //设置某列隐藏
            // dataGridView_ReportList.SetColVisible(new string[] { "PKID", "customer" });
            Dictionary<int, int> colWidth = new Dictionary<int, int>()
            {
                [0] = 30,
                [6] = 60,
            };
            ////设置列宽
            gridList1.SetColWidth(colWidth);
            for (int i = 0; i < 30; i++)
            {
                gridList1.Rows.Add(Properties.Resources.excel, "dsf", "dfsfs", "dsfsdf", "dfsf", "dfsf", "dfsfs");
 
            }

  效果:

 

 项目中的效果图:

 

 

posted @   代码如风~~~  阅读(119)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在外漂泊的这几年总结和感悟,展望未来
· 博客园 & 1Panel 联合终身会员上线
· 支付宝事故这事儿,凭什么又是程序员背锅?有没有可能是这样的...
· https证书一键自动续期,帮你解放90天限制
· 在 ASP.NET Core WebAPI如何实现版本控制?
历史上的今天:
2021-03-18 U3D PC端桌面应用程序远程升级
点击右上角即可分享
微信分享提示