DataGridView自定义列

合集下载

datagridview技巧

datagridview技巧

datagridview技巧DataGridView是Windows Forms中常用的控件之一,可以在应用程序中展示和编辑表格数据。

下面介绍一些DataGridView的技巧。

1. 在DataGridView中添加数据:可以通过代码动态添加数据,也可以将数据源绑定到DataGridView上。

使用DataSource属性可以绑定数据源,也可以手动遍历数据,使用Rows和Cells属性来添加数据。

2. 设置列样式:可以通过DataGridView的Column属性设置列的样式和属性,如宽度、标题文本、数据类型等。

还可以通过DefaultCellStyle属性设置列的默认单元格样式。

3. 单元格格式和数据验证:可以通过CellFormatting事件来自定义单元格的显示格式,如日期格式、货币格式等。

还可以通过CellValidating事件来验证用户输入的数据,并给出提示。

4. 排序和筛选:可以通过Sort方法对DataGridView中的数据进行排序。

还可以使用AutoFilter属性启用或禁用列标题的自动筛选功能,方便用户筛选数据。

5. 选择和编辑:可以通过SelectionMode属性设置选择模式,如单选、多选等。

还可以通过ReadOnly属性设置是否允许用户编辑单元格。

另外,还可以通过SelectedCells和SelectedRows属性获取用户选择的单元格或行。

6. 自定义单元格和行样式:可以通过CellPainting和RowPostPaint事件来自定义单元格和行的样式,如背景色、字体等。

可以根据特定的条件来改变单元格或行的样式,以提升用户体验。

7. 导出数据:可以通过DataGridView的GetClipboardContent方法将DataGridView中的数据导出为文本或HTML格式,方便数据的导出和共享。

以上是一些常用的DataGridView技巧,希望对您有帮助。

datagridview用法

datagridview用法

DataGridView用法1.概述D a ta Gr id Vi ew是Wi n do ws Fo rm s中一种常用的控件,用于展示和编辑表格数据。

本文将介绍Da ta Gr id Vi ew的基本用法和常用功能。

2.基本用法2.1创建D a t a G r i d V i e w要使用D at aG ri dVi e w,首先需要在窗体上进行控件的创建和初始化。

可以通过拖拽控件到窗体上或者在代码中动态创建控件。

2.2数据绑定在D at aG ri dV ie w中展示数据通常需要进行数据绑定。

可以通过设置D a ta So ur ce属性来实现数据绑定,可以绑定Da ta Ta bl e、B i nd in gS ou rc e等数据源。

2.3列定义可以通过列定义来指定D at aG ri dV ie w中的列数、列名、列类型等属性。

可以使用Da ta Gr i dV ie w的Co lu mns集合来对列进行操作。

2.4行操作可以通过Da ta Gr idV i ew的R ow s集合对行进行操作,如添加、删除、插入等操作。

可以根据行索引或行对象进行操作。

3.常用功能3.1样式设置可以通过设置Da ta Gr i dV ie w的Ce ll Sty l e、C o lu mn He ad er De fau l tC el lS ty le、R ow H ea de rs De fa ul tCe l lS ty le等属性来设置样式,如背景色、字体、对齐方式等。

3.2单元格编辑D a ta Gr id Vi ew可以方便地对单元格进行编辑,可以根据需要设置单元格的可编辑性,只读属性等。

可以通过事件处理程序来实现特定单元格的编辑操作。

3.3排序和筛选D a ta Gr id Vi ew提供了对数据进行排序和筛选的功能。

可以通过设置A l lo wS or ti ng属性来启用排序功能,通过设置A l lo wU se rT oF il ter C ol um ns属性来启用筛选功能。

如何为DataGridView添加一个定制的Column Type.doc

如何为DataGridView添加一个定制的Column Type.doc

如何为DataGridView添加一个定制的Column Type这个例子实现了一个把数据中的Boolean值用Y或者N在DataGridView里面显示,步骤如下:1. 建立一个继承DataGridViewTextBoxCell的类,代码如下:using System;using System.Collections.Generic;using System.Text;using System.Windows.Forms;using System.Drawing;namespace com.Threes.CustomControl{public class DataGridViewBooleanCell : DataGridViewTextBoxCell{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){// Call the base class method to paint the default cell appearance.base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,value, “”, errorText, cellStyle,advancedBorderStyle, paintParts);if (value is Boolean && (bool)value == true){graph ics.DrawString(“Y”, cellStyle.Font, new SolidBrush(cellStyle.ForeColor), cellBounds.X, cellBounds.Y);}}}}2. 建立一个继承自DataGridViewColumn的类代码如下:using System;using System.Collections.Generic;using System.Text;using System.Windows.Forms;namespace com.Threes.CustomControl{public class DataGridViewBooleanColumn : DataGridViewColumn{public DataGridViewBooleanColumn(){this.CellTemplate = new DataGridViewBooleanCell();}}}然后把你的DataGridView里面的Boolean列的ColumnType 改成以上的这个就可以了。

DataGridView自定义控件类

DataGridView自定义控件类

DataGridView⾃定义控件类1public class clsWindowGird2 {3public static void Editcol(int iColumnCount, DataGridView Grid, string sCaption, string sName, int iWidth, bool bVisible, bool bEdit, DataGridViewColumnSortMode SortMode, GridColumnType ColumnType)4 {5 DataGridViewColumn column = new DataGridViewColumn();6switch (ColumnType)7 {8case GridColumnType.enCheckBox:9 column = new DataGridViewCheckBoxColumn();10 column.HeaderCell = new DataGridViewCheckBoxHeaderCell();11break;12case GridColumnType.enTextBox:13 column = new DataGridViewTextBoxColumn();//new DataGridViewTextBoxColumn();14break;15case GridColumnType.enComboBox:16 column = new DataGridViewComboBoxColumn();17break;18case GridColumnType.enButton:19 column = new DataGridViewDisableButtonColumn();20break;21case GridColumnType.enProgressBar:22 column = new DataGridViewProgressBarColumn();23break;24case GridColumnType.enDateTimePicker:25 column = new CalendarColumn();26break;27case GridColumnType.enWorkStatus:28 column = new WorkStatusColumn();29break;30case GridColumnType.enImage:31 column = new DataGridViewImageColumn();32break;33case GridColumnType.enBrighter:34 column = new BrighterColumn();35break;36case GridColumnType.enVolume:37 column = new VolumeColumn();38break;39case GridColumnType.enTrackBar:40 column = new TrackBarColumn();41break;42case GridColumnType.enTimeZone:43 column = new TimeZoneColumn();44break;45case GridColumnType.enVolumeTrackBar:46 column = new VolumeTrackBarColumn();47break;48case GridColumnType.enBrighterTrackBar:49 column = new BrighterTrackBarColumn();50break;51 }52switch (sCaption.Substring(0, 1))53 {54case"^":55 column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;56break;57case"<":58 column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;59break;60case">":61 column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;62break;63 }64 column.HeaderText = sCaption.Remove(0, 1);65 column.SortMode = SortMode;66 Grid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;6768 = sName;69 column.Visible = bVisible;70 column.ReadOnly = bEdit;71//column.Width = iWidth * int.Parse(font.Size.ToString());72 column.Width = iWidth;73 Grid.Columns.Add(column);74 }75public enum GridColumnType76 {77 enTextBox = 0, //⽂本框78 enComboBox = 1,//下拉框79 enCheckBox = 2,//复选框80 enButton = 3, //按钮81 enProgressBar = 4,//进度条82 enDateTimePicker = 5, //时间框83 enWorkStatus = 6, //⼯作状态图标⽂字84 enImage = 7, //图⽚框85 enBrighter = 8,//亮度图标⽂字86 enVolume = 9, //⾳量图标⽂字87 enVolumeTrackBar = 10, //调节⾳量带滑块88 enTimeZone = 11, //⾃定义控件89 enTrackBar = 12, //滑块90 enBrighterTrackBar = 13, //滑块91 }92#region可以启⽤(禁⽤)按钮的⾃定义Grid按钮列和单元格93public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn94 {95public DataGridViewDisableButtonColumn()96 {97this.CellTemplate = new DataGridViewDisableButtonCell();98 }99 }100public class DataGridViewDisableButtonCell : DataGridViewButtonCell101 {102private bool enabledValue;103public bool Enabled104 {105get106 {107return enabledValue;108 }109set110 {111 enabledValue = value;112 }113 }114115// 重写120return cell;121 }122123// 默认情况下,按钮可⽤124public DataGridViewDisableButtonCell()125 {126this.enabledValue = true;127 }128129protected override void Paint(Graphics graphics,130 Rectangle clipBounds, Rectangle cellBounds, int rowIndex,131 DataGridViewElementStates elementState, object value,132object formattedValue, string errorText,133 DataGridViewCellStyle cellStyle,134 DataGridViewAdvancedBorderStyle advancedBorderStyle,135 DataGridViewPaintParts paintParts)136 {137// 判断是否被禁⽤,如果被禁⽤,这绘制不可⽤的按钮样式138if (!this.enabledValue)139 {140//绘制背景141if ((paintParts & DataGridViewPaintParts.Background) ==142 DataGridViewPaintParts.Background)143 {144 SolidBrush cellBackground =145new SolidBrush(cellStyle.BackColor);146 graphics.FillRectangle(cellBackground, cellBounds);147 cellBackground.Dispose();148 }149150// 绘制边框151if ((paintParts & DataGridViewPaintParts.Border) ==152 DataGridViewPaintParts.Border)153 {154 PaintBorder(graphics, clipBounds, cellBounds, cellStyle,155 advancedBorderStyle);156 }157158// 计算按钮的绘制区域,⼤⼩等159 Rectangle buttonArea = cellBounds;160 Rectangle buttonAdjustment =161this.BorderWidths(advancedBorderStyle);162 buttonArea.X += buttonAdjustment.X;163 buttonArea.Y += buttonAdjustment.Y;164 buttonArea.Height -= buttonAdjustment.Height;165 buttonArea.Width -= buttonAdjustment.Width;166167// 绘制不可⽤情况下的按钮168 ButtonRenderer.DrawButton(graphics, buttonArea,169 PushButtonState.Disabled);170171// 绘制按钮⽂本172if (this.FormattedValue is String)173 {174 TextRenderer.DrawText(graphics,175 (string)this.FormattedValue,176this.DataGridView.Font,177 buttonArea, SystemColors.GrayText);178 }179 }180else181 {182// 绘制可⽤情况下的按钮183base.Paint(graphics, clipBounds, cellBounds, rowIndex,184 elementState, value, formattedValue, errorText,185 cellStyle, advancedBorderStyle, paintParts);186 }187 }188 }189#endregion;190191#region Grid添加进度条192public class DataGridViewProgressBarColumn : DataGridViewTextBoxColumn 193 {194public DataGridViewProgressBarColumn()195 {196this.CellTemplate = new DataGridViewProgressBarCell();197 }198public override DataGridViewCell CellTemplate199 {200get201 {202return base.CellTemplate;203 }204set205 {206if (!(value is DataGridViewProgressBarCell))207 {208throw new InvalidCastException("DataGridViewProgressBarCell");209 }210base.CellTemplate = value;211 }212 }213///<summary>214/// ProgressBar最⼤値215///</summary>216public int Maximum217 {218get219 {220return ((DataGridViewProgressBarCell)this.CellTemplate).Maximum;221 }222set223 {224if (this.Maximum == value)225return;226 ((DataGridViewProgressBarCell)this.CellTemplate).Maximum = value; 227228if (this.DataGridView == null)229return;230int rowCount = this.DataGridView.RowCount;231for (int i = 0; i < rowCount; i++)232 {233 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);234 ((DataGridViewProgressBarCell)r.Cells[this.Index]).Maximum = value; 235 }236 }237 }238///<summary>243get244 {245return ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum;246 }247set248 {249if (this.Mimimum == value)250return;251 ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum = value;252if (this.DataGridView == null)253return;254int rowCount = this.DataGridView.RowCount;255for (int i = 0; i < rowCount; i++)256 {257 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);258 ((DataGridViewProgressBarCell)r.Cells[this.Index]).Mimimum = value;259 }260 }261 }262public int BarValue263 {264get265 {266return ((DataGridViewProgressBarCell)this.CellTemplate).BarValue;267 }268set269 {270if (this.BarValue == value)271return;272 ((DataGridViewProgressBarCell)this.CellTemplate).BarValue = value;273if (this.DataGridView == null)274return;275int rowCount = this.DataGridView.RowCount;276for (int i = 0; i < rowCount; i++)277 {278 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);279 ((DataGridViewProgressBarCell)r.Cells[this.Index]).BarValue = value;280 }281 }282 }283 }284///<summary>285/// ProgressBarDataGridView286///</summary>287public class DataGridViewProgressBarCell : DataGridViewTextBoxCell288 {289public DataGridViewProgressBarCell()290 {291this.maximumValue = 100;292this.mimimumValue = 0;293 }294295296private int mValue = 0;297public int BarValue298 {299get300 {301return this.mValue;302 }303set304 {305this.mValue = value;306 }307 }308309private int maximumValue;310public int Maximum311 {312get313 {314return this.maximumValue;315 }316set317 {318this.maximumValue = value;319 }320 }321322private int mimimumValue;323public int Mimimum324 {325get326 {327return this.mimimumValue;328 }329set330 {331this.mimimumValue = value;332 }333 }334public override Type ValueType335 {336get337 {338return typeof(int);339 }340 }341public override object DefaultNewRowValue342 {343get344 {345return0;346 }347 }348public override object Clone()349 {350 DataGridViewProgressBarCell cell = (DataGridViewProgressBarCell)base.Clone(); 351 cell.Maximum = this.Maximum;352 cell.Mimimum = this.Mimimum;353return cell;354 }355356protected override void Paint(Graphics graphics,357 Rectangle clipBounds, Rectangle cellBounds,358int rowIndex, DataGridViewElementStates cellState,359object value, object formattedValue, string errorText,360 DataGridViewCellStyle cellStyle,361 DataGridViewAdvancedBorderStyle advancedBorderStyle,366 intValue = (int)value;367if (intValue < this.mimimumValue)368 intValue = this.mimimumValue;369if (intValue > this.maximumValue)370 intValue = this.maximumValue;371if (mValue != 0)372 {373 intValue = mValue;374 }375double rate = (double)(intValue - this.mimimumValue) / (this.maximumValue - this.mimimumValue);376if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border)377 {378this.PaintBorder(graphics, clipBounds, cellBounds,379 cellStyle, advancedBorderStyle);380 }381 Rectangle borderRect = this.BorderWidths(advancedBorderStyle);382 Rectangle paintRect = new Rectangle(383 cellBounds.Left + borderRect.Left,384 cellBounds.Top + borderRect.Top,385 cellBounds.Width - borderRect.Right,386 cellBounds.Height - borderRect.Bottom);387bool isSelected = (cellState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected;388 System.Drawing.Color bkColor;389if (isSelected && (paintParts & DataGridViewPaintParts.SelectionBackground) == DataGridViewPaintParts.SelectionBackground) 390 {391 bkColor = cellStyle.SelectionBackColor;392 }393else394 {395 bkColor = cellStyle.BackColor;396 }397if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background)398 {399using (SolidBrush backBrush = new SolidBrush(bkColor))400 {401 graphics.FillRectangle(backBrush, paintRect);402 }403 }404 paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);405 paintRect.Width -= cellStyle.Padding.Horizontal;406 paintRect.Height -= cellStyle.Padding.Vertical;407if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground)408 {409 Rectangle barBounds = new Rectangle(410 paintRect.Left, paintRect.Bottom - 3*cellBounds.Height/4,411 paintRect.Width, cellBounds.Height/2);412 barBounds.Width = (int)Math.Round(barBounds.Width * rate);413//ProgressBarRenderer.DrawHorizontalChunks(graphics, barBounds);414415 graphics.FillRectangle(System.Drawing.Brushes.Green, barBounds);416 barBounds = new Rectangle(417 paintRect.Left, paintRect.Bottom - cellBounds.Height,418 cellBounds.Width, cellBounds.Height);419 graphics.DrawRectangle(Pens.Wheat, barBounds);420//if (ProgressBarRenderer.IsSupported)421//{422////是否完全采⽤进度条的样式,此处主要修改了进度条的边框样式423////ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect);424// Rectangle barBounds = new Rectangle(425// paintRect.Left, paintRect.Bottom - 9,426// paintRect.Width, 9);427// barBounds.Width = (int)Math.Round(barBounds.Width * rate);428////ProgressBarRenderer.DrawHorizontalChunks(graphics, barBounds);429430// graphics.FillRectangle(System.Drawing.Brushes.Green, barBounds);431// barBounds = new Rectangle(432// paintRect.Left, paintRect.Bottom - 9,433// cellBounds.Width, 9);434// graphics.DrawRectangle(Pens.Wheat, barBounds);435//}436//else437//{438////采⽤控件的背景⾊439// System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(bkColor);440// graphics.FillRectangle(brush, paintRect);441////graphics.FillRectangle(Brushes.White, paintRect);442////graphics.DrawRectangle(Pens.Black, paintRect);443// Rectangle barBounds = new Rectangle(444// paintRect.Left + 1, paintRect.Top + 1,445// paintRect.Width - 1, paintRect.Height - 1);446// barBounds.Width = (int)Math.Round(barBounds.Width * rate);447// graphics.FillRectangle(System.Drawing.Brushes.BurlyWood, barBounds);448//}449 }450if (this.DataGridView.CurrentCellAddress.X == this.ColumnIndex &&451this.DataGridView.CurrentCellAddress.Y == this.RowIndex &&452 (paintParts & DataGridViewPaintParts.Focus) ==453 DataGridViewPaintParts.Focus &&454this.DataGridView.Focused)455 {456457 Rectangle focusRect = paintRect;458 focusRect.Inflate(-3, -3);459 ControlPaint.DrawFocusRectangle(graphics, focusRect);460 }461if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground)462 {463if (value != null)464 {465//if (Math.Round(rate * 100) > 0 && Math.Round(rate * 100) <= 100)466//{467//string txt = string.Format("{0}%", Math.Round(rate * 100));468string txt = value.ToString();469 TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;470 System.Drawing.Color fColor = cellStyle.ForeColor;471 paintRect.Inflate(-2, -2);472 TextRenderer.DrawText(graphics, txt, cellStyle.Font,473 paintRect, fColor, flags);474//}475 }476 }477if ((paintParts & DataGridViewPaintParts.ErrorIcon) ==478 DataGridViewPaintParts.ErrorIcon &&479this.DataGridView.ShowCellErrors &&480 !string.IsNullOrEmpty(errorText))481 {482 Rectangle iconBounds = this.GetErrorIconBounds(483 graphics, cellStyle, rowIndex);484 iconBounds.Offset(cellBounds.X, cellBounds.Y);490491#region Grid添加⼯作状态控件492public class WorkStatusColumn : DataGridViewTextBoxColumn493 {494public WorkStatusColumn()495 {496this.CellTemplate = new WorkStatusCell();497 }498public override DataGridViewCell CellTemplate499 {500get501 {502return base.CellTemplate;503 }504set505 {506if (!(value is WorkStatusCell))507 {508throw new InvalidCastException("DataGridViewVolumeCell"); 509 }510base.CellTemplate = value;511 }512 }513///<summary>514/// ProgressBar最⼤値515///</summary>516public int Maximum517 {518get519 {520return ((WorkStatusCell)this.CellTemplate).Maximum;521 }522set523 {524if (this.Maximum == value)525return;526 ((WorkStatusCell)this.CellTemplate).Maximum = value;527528if (this.DataGridView == null)529return;530int rowCount = this.DataGridView.RowCount;531for (int i = 0; i < rowCount; i++)532 {533 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i); 534 ((WorkStatusCell)r.Cells[this.Index]).Maximum = value;535 }536 }537 }538///<summary>539/// ProgressBar最⼩値540///</summary>541public int Mimimum542 {543get544 {545return ((WorkStatusCell)this.CellTemplate).Mimimum;546 }547set548 {549if (this.Mimimum == value)550return;551 ((WorkStatusCell)this.CellTemplate).Mimimum = value;552if (this.DataGridView == null)553return;554int rowCount = this.DataGridView.RowCount;555for (int i = 0; i < rowCount; i++)556 {557 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i); 558 ((WorkStatusCell)r.Cells[this.Index]).Mimimum = value;559 }560 }561 }562public int BarValue563 {564get565 {566return ((WorkStatusCell)this.CellTemplate).BarValue;567 }568set569 {570if (this.BarValue == value)571return;572 ((WorkStatusCell)this.CellTemplate).BarValue = value;573if (this.DataGridView == null)574return;575int rowCount = this.DataGridView.RowCount;576for (int i = 0; i < rowCount; i++)577 {578 DataGridViewRow r = this.DataGridView.Rows.SharedRow(i); 579 ((WorkStatusCell)r.Cells[this.Index]).BarValue = value;580 }581 }582 }583 }584///<summary>585///WorkStatusCell586///</summary>587public class WorkStatusCell : DataGridViewTextBoxCell588 {589public WorkStatusCell()590 {591this.maximumValue = 1;592this.mimimumValue = 0;593 }594595596private int mValue = 0;597public int BarValue598 {599get600 {601return this.mValue;602 }603set604 {605this.mValue = value;606 }607 }613 {614return this.maximumValue;615 }616set617 {618this.maximumValue = value;619 }620 }621622private int mimimumValue;623public int Mimimum624 {625get626 {627return this.mimimumValue;628 }629set630 {631this.mimimumValue = value;632 }633 }634public override Type ValueType635 {636get637 {638return typeof(int);639 }640 }641public override object DefaultNewRowValue642 {643get644 {645return0;646 }647 }648public override object Clone()649 {650 WorkStatusCell cell = (WorkStatusCell)base.Clone();651 cell.Maximum = this.Maximum;652 cell.Mimimum = this.Mimimum;653return cell;654 }655656protected override void Paint(Graphics graphics,657 Rectangle clipBounds, Rectangle cellBounds,658int rowIndex, DataGridViewElementStates cellState,659object value, object formattedValue, string errorText,660 DataGridViewCellStyle cellStyle,661 DataGridViewAdvancedBorderStyle advancedBorderStyle,662 DataGridViewPaintParts paintParts)663 {664int intValue = 0;665if (value is int)666 intValue = (int)value;667//if (intValue < this.mimimumValue)668// intValue = this.mimimumValue;669//if (intValue > this.maximumValue)670// intValue = this.maximumValue;671if (mValue != 0)672 {673 intValue = mValue;674 }675double rate = (double)(intValue - this.mimimumValue) / (this.maximumValue - this.mimimumValue);676if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border)677 {678this.PaintBorder(graphics, clipBounds, cellBounds,679 cellStyle, advancedBorderStyle);680 }681 Rectangle borderRect = this.BorderWidths(advancedBorderStyle);682 Rectangle paintRect = new Rectangle(683 cellBounds.Left + borderRect.Left,684 cellBounds.Top + borderRect.Top,685 cellBounds.Width - borderRect.Right,686 cellBounds.Height - borderRect.Bottom);687bool isSelected = (cellState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected;688 System.Drawing.Color bkColor;689if (isSelected && (paintParts & DataGridViewPaintParts.SelectionBackground) == DataGridViewPaintParts.SelectionBackground)690 {691 bkColor = cellStyle.SelectionBackColor;692 }693else694 {695 bkColor = cellStyle.BackColor;696 }697if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background)698 {699using (SolidBrush backBrush = new SolidBrush(bkColor))700 {701 graphics.FillRectangle(backBrush, paintRect);702 }703 }704 paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);705 paintRect.Width -= cellStyle.Padding.Horizontal;706 paintRect.Height -= cellStyle.Padding.Vertical;707if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground)708 {709//Rectangle barBounds = new Rectangle(710// paintRect.Left, paintRect.Bottom - cellBounds.Height,711// 40, cellBounds.Height);712if (intValue == 0)713 {714//graphics.DrawImage(Properties.Resources.btncheckoff, paintRect.X+cellBounds.Size.Width/4, paintRect.Bottom - 3*cellBounds.Height / 4 , 60,15);715 graphics.DrawImage(Properties.Resources.btncheckoff, paintRect.X + cellBounds.Size.Width / 4, paintRect.Bottom - cellBounds.Height, 60, cellBounds.Size.Height); 716717 }718else719 {720//graphics.DrawImage(Properties.Resources.btncheckon, paintRect.X + cellBounds.Size.Width / 4, paintRect.Bottom - 3 * cellBounds.Height / 4, 60, 15);721 graphics.DrawImage(Properties.Resources.btncheckon, paintRect.X + cellBounds.Size.Width / 4, paintRect.Bottom - cellBounds.Height, 60, cellBounds.Size.Height); 722 }723 }724if (this.DataGridView.CurrentCellAddress.X == this.ColumnIndex &&725this.DataGridView.CurrentCellAddress.Y == this.RowIndex &&726 (paintParts & DataGridViewPaintParts.Focus) ==727 DataGridViewPaintParts.Focus &&728this.DataGridView.Focused)729 {730735if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground)736 {737if (value != null)738 {739740string txt = value.ToString();741//TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;742 System.Drawing.Color fColor = cellStyle.ForeColor;743 paintRect.Inflate(-2, -2);744//TextRenderer.DrawText(graphics, txt, cellStyle.Font, paintRect, fColor, flags);745 }746 }747if ((paintParts & DataGridViewPaintParts.ErrorIcon) ==748 DataGridViewPaintParts.ErrorIcon &&749this.DataGridView.ShowCellErrors &&750 !string.IsNullOrEmpty(errorText))751 {752 Rectangle iconBounds = this.GetErrorIconBounds(753 graphics, cellStyle, rowIndex);754 iconBounds.Offset(cellBounds.X, cellBounds.Y);755this.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText);756 }757 }758 }759#endregion760761#region Grid添加⽇期控件762public class CalendarCell : DataGridViewTextBoxCell763 {764public CalendarCell()765 : base()766 {767//使⽤简短⽇期格式.768this.Style.Format = "HH:mm:ss";769 }770public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) 771 {772//将编辑控件的值设置成当前单元格的值.773base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);774//775 CalendarEditingControl ctl = DataGridView.EditingControl as CalendarEditingControl;776try777 {778 ctl.Value = (DateTime)this.Value;779 }780catch (Exception)781 {782/*当数据库中对应⽇期为空(⽐如在添加数据时),在这⾥设置⽇期的默认值。

DataGridView自动设定列宽和行高

DataGridView自动设定列宽和行高

DataGridView⾃动设定列宽和⾏⾼设定⾏⾼和列宽⾃动调整设定包括Header和所有单元格的列宽⾃动调整//设置包括Header和所有单元格的列宽⾃动调整this.dgv_PropDemo.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;设定包括Header和所有单元格的⾏⾼⾃动调整//设置包括Header和所有单元格的⾏⾼⾃动调整this.dgv_PropDemo.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;设置第⼀列⾃动调整//第⼀列⾃动调整this.dgv_PropDemo.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;设置DataGridView所有列宽⾃动调整this.dgv_PropDemo.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);设置DataGridView第⼀列的列宽⾃动调整this.dgv_PropDemo.AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.DisplayedCells);设置DataGridView第⼀⾏⾃动调整⾏⾼this.dgv_PropDemo.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);关于性能:通过AutoSizeColumnsMode和AutoSizeRowsMode属性所指定的单元格进⾏⾃动调整时,如果调整次数过多那么将可能导致性能的下降,尤其是在⾏和列数⽐较多的情况下,因为每调整⼀次就会调⽤底层的API进⾏重绘。

C#如何自定义DataGridViewColumn来显示TreeView

C#如何自定义DataGridViewColumn来显示TreeView

C#如何自定义DataGridViewColumn来显示TreeView我们可以自定义DataGridView的DataGridViewColumn来实现自定义的列,下面介绍一下如何通过扩展DataGridViewColumn来实现一个TreeViewColumn1 TreeViewColumn类TreeViewColumn继承自DataGridViewColumn,为了动态给TreeViewColumn传入一个TreeView,这里暴露出一个公共属性_root,可以绑定一个初始化的TreeView. 另外需要重写DataGridCell类型的CellT emplate,这里返还一个TreeViewCell (需要自定义)复制代码1 /// <summary>2 /// Host TreeView In DataGridView Cell3 /// </summary>4 public class TreeViewColumn : DataGridViewColumn5 {6 public TreeViewColumn()7 : base(new TreeViewCell())8 {9 }10 [Description("Set TreeView Root in DataGridView Cell"), Category("TreeView")]11 public TreeView _root12 {13 get{return Roots.tree;}14 set{Roots.tree=value;}15 }16 public override DataGridViewCell CellT emplate17 {18 get19 {20 return base.CellT emplate;21 }22 set23 {24 // Ensure that the cell used for the template is a TreeViewCell.25 if (value != null &&26 !value.GetType().IsAssignableFrom(typeof(TreeViewCell)))27 {28 throw new InvalidCastException("Must be a TreeViewCell");29 }30 base.CellTemplate = value;31 }32 }33 }复制代码2 TreeViewCell类上面TreeViewColumn重写了CellTemplate,返回的就是自定义的TreeViewCell,这里就是具体实现其逻辑。

DataGridview 控件绑定数据时怎么显示为自定义列名

DataGridview 控件绑定数据时怎么显示为自定义列名

datagridview控件绑定数据时怎么显示为自定义列名?比如说:我有个sql表是ssskyjsj,有4个列,列名分别为zj_xh, dahm, gw, syry,datagridview控件显示为所有的信息,包括zj_xh, dahm, gw, syry,datagridview都显示出来了,我想让datagridview控件显示的列名为序号,档案号码,岗位,使用人员这个样字的,该咋办呢?,数据显示一般为以下两步:1、通过DataAdapter将查询的结果填充到DataSet的表(DataTable)中,如:dataAdapter.Fill(dataSet),这时dataSet的表名默认为Table,如果使用批处理查询并将得到的结果填入dataSet中则表名默认为Table,Table1,Table2……2、将显示控件(如DataGridView)的DataSource静态或动态的设置成该表;如:dataGridView1.DataSource = DataSet[A].Tables["tableName"];此结果显示出来的列名为实际数据库中的列名,而一般在数据库里的字段名都是英文或拼音的简写,所以我们有必要用便于用户理解的字段名显示在交互界面上。

琢磨了一下有如下三种方法,这三种方法都是我实际验证过的,特别是映射,网上的许多通不过,我发的代码是我琢磨了一天才搞出来(我是只菜鸟,刚学):1、直接修改表的列名,我认为这是一种最简单,最方便,也可通过类实现(多个显示页面时)的方法:实现语句:ds.Tables[0].Columns["zj_xh"].ColumnName = "序号"全部代码如下:private void button1_Click ( object sender, EventArgs e ) //方法1{ClsDB.ClsDBControl cb = new ClsDB.ClsDBControl(); //实例化连接类SqlConnection connection = cb.ConDb();//建立连接string strSql = "select * from ssskyjsj"; //sql 语句SqlDataAdapter da = new SqlDataAdapter(); // 实例化适配器SqlCommand sqlcmd=new SqlCommand (strSql ,connection ); //sql命令da.SelectCommand = sqlcmd; //使用SqlDataAdapter的查询DataSet ds = new DataSet(); // 用DataSet方式ds.Clear();da.Fill(ds);//修改填充表的列名ds.Tables[0].Columns["zj_xh"].ColumnName ="序号";ds.Tables[0].Columns["dahm"].ColumnName = "档案号码";ds.Tables[0].Columns["gw"].ColumnName = "岗位";ds.Tables[0].Columns["syry"].ColumnName = "使用人员";this.dataGridView1.DataSource = ds.Tables[0].DefaultView;if (connection.State == ConnectionState.Open)connection.Close();// 关闭连接}2、在sql语句中,给源表的列加中文列名方法:将方法1中的语句:string strSql = "select * from sqltable";变为:string strSql = "select zj_xh as '序号',dahm as '档案号码',gw as '岗位',syry as '使用人员' from ssskyjsj";完整代码如下:private void button4_Click ( object sender, EventArgs e ) //方法二:给查询语句的列名加中文别名 {ClsDB.ClsDBControl cb = new ClsDB.ClsDBControl(); //实例化连接类SqlConnection connection = cb.ConDb();//建立连接string strSql = "select zj_xh as '序号',dahm as '档案号码',gw as '岗位',syry as '使用人员' from sqltable"; //sql 语句SqlDataAdapter da = new SqlDataAdapter(); // 实例化适配器SqlCommand sqlcmd = new SqlCommand(strSql, connection); //sql命令da.SelectCommand = sqlcmd; //使用SqlDataAdapter的查询DataSet ds = new DataSet(); // 用 DataSet 方式ds.Clear();try{da.Fill(ds);this.dataGridView1.DataSource = ds.Tables[0].DefaultView;//MessageBox.Show("ok!");}catch{MessageBox.Show("error!");}if (connection.State == ConnectionState.Open)connection.Close();// 关闭连接}3、映射每一次用DataAdapter来填充DataSet时,都是根据构架来填充数据的.如果想把DataSet中的数据表和表列名根据自己得情况定义一个映射, 如把英文表名称更换成中文表名,把英文列名更换成中文列表,就需要在DataAdapter中进行表映射和列名映射.表映射方法及完整代码如下:private void button1_Click_1 ( object sender, EventArgs e ) //方法三:通过映射表及中文列名来显示sql表内容{ClsDB.ClsDBControl cb = new ClsDB.ClsDBControl(); //实例化连接类SqlConnection connection = cb.ConDb();//建立连接string strSql = "select * from sqltable"; //sql 语句SqlDataAdapter da = new SqlDataAdapter(); // 实例化适配器SqlCommand sqlcmd = new SqlCommand(strSql, connection); //sql命令da.SelectCommand = sqlcmd; //使用SqlDataAdapter的查询DataSet ds = new DataSet(); // 用 DataSet 方式ds.Clear();// 映射//DestTable 为设定的ds 中的用da填充的表名,为映射源表, DestTable 为映射表名(有点象视图view)// 1 表映射// 语法:DataAdapter.TableMappings.Add(SourceTable,DestTable);da.TableMappings.Add("SourceTable", "DestTable");da.TableMappings.Add("DestTable", "DestTable"); //这一步不能省,否则在下面的列名映射时会提示找//DestTable表//da.Fill(ds, "DestTable");//填充源表//2 列映射// 语法: dataAdapter.TableMapping[DestTable].ColumnMappings.Add(sourceField,destField);;// 注意:TableMappings 是属性,故后面带方括号,我曾用成圆括号(),找好久才发现这个错误da.TableMappings["DestTable"].ColumnMappings.Add("zj_xh", "序号");da.TableMappings["DestTable"].ColumnMappings.Add("dahm", "档案号码");da.TableMappings["DestTable"].ColumnMappings.Add("gw", "岗位");da.TableMappings["DestTable"].ColumnMappings.Add("syry", "使用人员");da.Fill(ds, "DestTable");//填充表,注意 1、该条语句只能在这个位置,放在前面,可显示内容,但不能映射列名; 2、只能用da.Fill(ds, "DestTable"),而不能用 da.Fill(ds, "SourceTable")try{this.dataGridView1.DataSource = ds;this.dataGridView1.DataMember = "DestTable";//MessageBox.Show("ok!");}catch{MessageBox.Show("error!");}if (connection.State == ConnectionState.Open)connection.Close();// 关闭连接}。

C#中DataGridView控件使用大全

C#中DataGridView控件使用大全

DataGridView动态添加新行:DataGridView控件在实际应用中非常实用,特别需要表格显示数据时。

可以静态绑定数据源,这样就自动为DataGridView控件添加相应的行。

假如需要动态为DataGridView控件添加新行,方法有很多种,下面简单介绍如何为DataGridView控件动态添加新行的两种方法:方法一:int index=this.dataGridView1.Rows.Add();this.dataGridView1.Rows[index].Cells[0].Value = "1";this.dataGridView1.Rows[index].Cells[1].Value = "2";this.dataGridView1.Rows[index].Cells[2].Value = "监听";利用dataGridView1.Rows.Add()事件为DataGridView控件增加新的行,该函数返回添加新行的索引号,即新行的行号,然后可以通过该索引号操作该行的各个单元格,如dataGridView1.Rows[index].Cells[0].Value = "1"。

这是很常用也是很简单的方法。

方法二:DataGridViewRow row = new DataGridViewRow(); DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell(); textboxcell.Value = "aaa";row.Cells.Add(textboxcell);DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell(); row.Cells.Add(comboxcell);dataGridView1.Rows.Add(row);方法二比方法一要复杂一些,但是在一些特殊场合非常实用,例如,要在新行中的某些单元格添加下拉框、按钮之类的控件时,该方法很有帮助。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Winform下DataGridView控件自定义列System.Windows.Forms.DataGridView控件是net下,数据显示使用最多的控件之一,但是Datagridviewk控件列类型却仅仅只有6中分别是button 、checkbox、combobox、image、link、textbox 等6种常见类型。

这很难满足我们日常开发需要。

如果需要复杂的应用,要么找第三方控件,要么只能自己开发。

而功能强大的第三方控件往往是需要付费的。

但我们开发需要的很可能只是简单的功能,如果为了某个简单功能而专门购买一个控件对于个人来说有些得不偿失。

那么我们只剩下自己开发一途。

幸运的是DataGridView控件容许我们进行二次开发,可以自定义我们需要的控件列。

下图就是自定义日期输入自定义列,通过下面的例子,你完全可以开发出自己需要的功能列。

下面给出和C#代码和原理自定义列必须自己写三个类,这三个类必须继承系统标准的类或实现系统标准接口。

这三个类实际上代表gridview控件中的列、列中的单元格、以及单元格中的具体控件分别继承自系统1、DataGridViewColumn 代表表格中的列2、DataGridViewTextBoxCell 代表列中的单元格3、IDataGridViewEditingControl 接口,单元格控件可以几本可以继承自任何标准控件或者自定义控件,但是必须实现IDataGridViewEditingControl下面给出vb和C#的详细案例代码一、C# 代码using System;using System.Windows.Forms;public class CalendarColumn : DataGridViewColumn{public CalendarColumn() : base(new CalendarCell()){}public override DataGridViewCell CellTemplate{get{return base.CellTemplate;}set{// Ensure that the cell used for the template is a CalendarCell.if (value != null &&!value.GetType().IsAssignableFrom(typeof(CalendarCell ))){throw new InvalidCastException("Must be a CalendarCell");}base.CellTemplate = value;}}}public class CalendarCell : DataGridViewTextBoxCell{public CalendarCell(): base(){// Use the short date format.this.Style.Format = "d";}public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle){// Set the value of the editing control to the current cell value.base.InitializeEditingControl(rowIndex, initialFormattedValue,dataGridViewCellStyle);CalendarEditingControl ctl =DataGridView.EditingControl as CalendarEditingControl;ctl.Value = (DateTime)this.Value;}public override Type EditType{get{// Return the type of the editing contol that CalendarCell uses.return typeof(CalendarEditingControl);}}public override Type ValueType{get{// Return the type of the value that CalendarCell contains.return typeof(DateTime);}}public override object DefaultNewRowValue{get{// Use the current date and time as the default value.return DateTime.Now;}}}class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl{DataGridView dataGridView;private bool valueChanged = false;int rowIndex;public CalendarEditingControl(){this.Format = DateTimePickerFormat.Short;}// Implements theIDataGridViewEditingControl.EditingControlFormattedValue // property.public object EditingControlFormattedValue{get{return this.Value.ToShortDateString();}set{String newValue = value as String;if (newValue != null){this.Value = DateTime.Parse(newValue);}}}// Implements the// IDataGridViewEditingControl.GetEditingControlFormattedValue method.public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context){return EditingControlFormattedValue;}// Implements the// IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle){this.Font = dataGridViewCellStyle.Font;this.CalendarForeColor = dataGridViewCellStyle.ForeColor;this.CalendarMonthBackground =dataGridViewCellStyle.BackColor;}// Implements theIDataGridViewEditingControl.EditingControlRowIndex// property.public int EditingControlRowIndex{get{return rowIndex;}set{rowIndex = value;}}// Implements theIDataGridViewEditingControl.EditingControlWantsInputKey // method.public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey){// Let the DateTimePicker handle the keys listed.switch (key & Keys.KeyCode){case Keys.Left:case Keys.Up:case Keys.Down:case Keys.Right:case Keys.Home:case Keys.End:case Keys.PageDown:case Keys.PageUp:return true;default:return false;}}// Implements theIDataGridViewEditingControl.PrepareEditingControlForEdit // method.public void PrepareEditingControlForEdit(bool selectAll) {// No preparation needs to be done.}// Implements the IDataGridViewEditingControl// .RepositionEditingControlOnValueChange property.public bool RepositionEditingControlOnValueChange{get{return false;}}// Implements the IDataGridViewEditingControl// .EditingControlDataGridView property.public DataGridView EditingControlDataGridView{get{return dataGridView;}set{dataGridView = value;}}// Implements the IDataGridViewEditingControl// .EditingControlValueChanged property.public bool EditingControlValueChanged{get{return valueChanged;}set{valueChanged = value;}}// Implements the IDataGridViewEditingControl// .EditingPanelCursor property.public Cursor EditingPanelCursor{get{return base.Cursor;}}protected override void OnValueChanged(EventArgs eventargs){// Notify the DataGridView that the contents of the cell// have changed.valueChanged = true;this.EditingControlDataGridView.NotifyCurrentCellDirty(true);base.OnValueChanged(eventargs);}}public class Form1 : Form{private DataGridView dataGridView1 = new DataGridView();[STAThreadAttribute()]public static void Main(){Application.Run(new Form1());}public Form1(){this.dataGridView1.Dock = DockStyle.Fill;this.Controls.Add(this.dataGridView1);this.Load += new EventHandler(Form1_Load);this.Text = "DataGridView calendar column demo";}private void Form1_Load(object sender, EventArgs e){CalendarColumn col = new CalendarColumn();this.dataGridView1.Columns.Add(col);this.dataGridView1.RowCount = 5;foreach (DataGridViewRow row in this.dataGridView1.Rows) {row.Cells[0].Value = DateTime.Now;}}}二、VB代码Imports SystemImports System.Windows.FormsPublic Class CalendarColumnInherits DataGridViewColumnPublic Sub New()MyBase.New(New CalendarCell())End SubPublic Overrides Property CellTemplate() As DataGridViewCell GetReturn MyBase.CellTemplateEnd GetSet(ByVal value As DataGridViewCell)' Ensure that the cell used for the template is a CalendarCell.If Not (value Is Nothing) AndAlso _Notvalue.GetType().IsAssignableFrom(GetType(CalendarCell)) _ThenThrow New InvalidCastException("Must be a CalendarCell")End IfMyBase.CellTemplate = valueEnd SetEnd PropertyEnd ClassPublic Class CalendarCellInherits DataGridViewTextBoxCellPublic Sub New()' Use the short date format.Me.Style.Format = "d"End SubPublic Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _ByVal initialFormattedValue As Object, _ByVal dataGridViewCellStyle As DataGridViewCellStyle)' Set the value of the editing control to the current cell value.MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _dataGridViewCellStyle)Dim ctl As CalendarEditingControl = _CType(DataGridView.EditingControl, CalendarEditingControl)ctl.Value = CType(Me.Value, DateTime)End SubPublic Overrides ReadOnly Property EditType() As TypeGet' Return the type of the editing contol that CalendarCell uses.Return GetType(CalendarEditingControl)End GetEnd PropertyPublic Overrides ReadOnly Property ValueType() As TypeGet' Return the type of the value that CalendarCell contains.Return GetType(DateTime)End GetEnd PropertyPublic Overrides ReadOnly Property DefaultNewRowValue() As Object Get' Use the current date and time as the default value.Return DateTime.NowEnd GetEnd PropertyEnd ClassClass CalendarEditingControlInherits DateTimePickerImplements IDataGridViewEditingControlPrivate dataGridViewControl As DataGridViewPrivate valueIsChanged As Boolean = FalsePrivate rowIndexNum As IntegerPublic Sub New()Me.Format = DateTimePickerFormat.ShortEnd SubPublic Property EditingControlFormattedValue() As Object _ ImplementsIDataGridViewEditingControl.EditingControlFormattedValueGetReturn Me.Value.ToShortDateString()End GetSet(ByVal value As Object)If TypeOf value Is [String] ThenMe.Value = DateTime.Parse(CStr(value))End IfEnd SetEnd PropertyPublic Function GetEditingControlFormattedValue(ByVal context _ As DataGridViewDataErrorContexts) As Object _ImplementsIDataGridViewEditingControl.GetEditingControlFormattedValue Return Me.Value.ToShortDateString()End FunctionPublic Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As _DataGridViewCellStyle) _ImplementsIDataGridViewEditingControl.ApplyCellStyleToEditingControlMe.Font = dataGridViewCellStyle.FontMe.CalendarForeColor = dataGridViewCellStyle.ForeColorMe.CalendarMonthBackground = dataGridViewCellStyle.BackColor End SubPublic Property EditingControlRowIndex() As Integer _Implements IDataGridViewEditingControl.EditingControlRowIndexGetReturn rowIndexNumEnd GetSet(ByVal value As Integer)rowIndexNum = valueEnd SetEnd PropertyPublic Function EditingControlWantsInputKey(ByVal key As Keys, _ ByVal dataGridViewWantsInputKey As Boolean) As Boolean _ImplementsIDataGridViewEditingControl.EditingControlWantsInputKey' Let the DateTimePicker handle the keys listed.Select Case key And Keys.KeyCodeCase Keys.Left, Keys.Up, Keys.Down, Keys.Right, _Keys.Home, Keys.End, Keys.PageDown, Keys.PageUpReturn TrueCase ElseReturn FalseEnd SelectEnd FunctionPublic Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _ImplementsIDataGridViewEditingControl.PrepareEditingControlForEdit' No preparation needs to be done.End SubPublic ReadOnly Property RepositionEditingControlOnValueChange() _ As Boolean Implements _IDataGridViewEditingControl.RepositionEditingControlOnValueChangeGetReturn FalseEnd GetEnd PropertyPublic Property EditingControlDataGridView() As DataGridView _ ImplementsIDataGridViewEditingControl.EditingControlDataGridViewGetReturn dataGridViewControlEnd GetSet(ByVal value As DataGridView)dataGridViewControl = valueEnd SetEnd PropertyPublic Property EditingControlValueChanged() As Boolean _ ImplementsIDataGridViewEditingControl.EditingControlValueChangedGetReturn valueIsChangedEnd GetSet(ByVal value As Boolean)valueIsChanged = valueEnd SetEnd PropertyPublic ReadOnly Property EditingControlCursor() As Cursor _ Implements IDataGridViewEditingControl.EditingPanelCursorGetReturn MyBase.CursorEnd GetEnd PropertyProtected Overrides Sub OnValueChanged(ByVal eventargs As EventArgs)' Notify the DataGridView that the contents of the cell have changed.valueIsChanged = TrueMe.EditingControlDataGridView.NotifyCurrentCellDirty(True)MyBase.OnValueChanged(eventargs)End SubEnd ClassPublic Class Form1Inherits FormPrivate dataGridView1 As New DataGridView()<STAThreadAttribute()> _Public Shared Sub Main()Application.Run(New Form1())End SubPublic Sub New()Me.dataGridView1.Dock = DockStyle.FillMe.Controls.Add(Me.dataGridView1)Me.Text = "DataGridView calendar column demo"End SubPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _Handles Me.LoadDim col As New CalendarColumn()Me.dataGridView1.Columns.Add(col)Me.dataGridView1.RowCount = 5Dim row As DataGridViewRowFor Each row In Me.dataGridView1.Rowsrow.Cells(0).Value = DateTime.NowNext row End SubEnd Class。

相关文档
最新文档