NET新手指南:轻松自定义DataGridView控件
.NET4.0 使用GridView控件

4.0 使用GridView控件在Visual Studio 2010中,用户可以采用可视化的方式为页面插入GridView控件,也可以通过代码的方式插入GridView控件。
1.添加GridView控件在页面的【设计】视图中选择任意一个段落,然后即可从【工具箱】中选择【GridView控件】,将其插入到页面中,如图10-2所示。
图10-2 插入的GridView控件2.更改控件外观通过可视化的方法,可以方便地改变GridView控件的外观,为其应用各种模板样式。
选中GridView控件或将鼠标滑至GridView控件上方,然后即可单击控件右上角的【GridView 任务】按钮,如图10-3所示。
图10-3 单击任务按钮在弹出的【GridView 任务】菜单中执行【自动套用格式】命令,如图10-4所示。
图10-4 执行【自动套用格式】命令然后,即可在弹出的【自动套用格式】对话框中选择GridView控件的格式架构,如图10-5所示。
图10-5 选择套用的格式3.添加数据源数据绑定控件的最大特点就是允许方便地与数据库中的数据进行绑定,快速显示数据内容。
用同样的方式选择GridView控件,单击其右上角的【GridView 任务】按钮,打开【GridView 任务】菜单。
如果当前的项目已绑定了数据源,则在该菜单中【选择数据源】的菜单中即可显示这些数据源。
否则,开发者可以在【选择数据源】的菜单中选择“<新建数据源>”选项,连接一个新的数据源,如图10-6所示。
图10-6 新建数据源在弹出的【数据源配置向导】对话框中选择对应的数据源类型,然后即可设置数据源的编号索引,单击【确定】按钮,如图10-7所示。
图10-7 选择数据源在弹出的【配置数据源】对话框中单击【新建连接】按钮,建立一个新的数据源连接,如图10-8所示。
图10-8 新建数据源连接在弹出的【添加连接】对话框中,输入数据库服务器的名称,并选择服务器安全的验证方式,如图10-9所示。
NET中DataGridView数据绑定方法详解

NET中DataGridView数据绑定方法详解
1.使用数据集进行数据绑定
-创建一个数据集对象,并指定相应的表结构。
-从数据库中填充数据到数据集中。
- 将DataGridView的数据源属性设置为数据集中的表。
- 设置DataGridView的自动列生成属性为True,以自动生成列。
2.使用数据表进行数据绑定
数据表是数据集中的一种结构,它由行和列组成。
使用数据表进行数据绑定的步骤如下:
-创建一个数据表对象,并定义列名称和类型。
-从数据库中填充数据到数据表中。
- 将DataGridView的数据源属性设置为数据表。
3. 使用BindingSource进行数据绑定
- 创建一个BindingSource对象。
- 设置BindingSource的DataSource属性为数据源。
- 将BindingSource绑定到DataGridView的数据源属性上。
4.使用数据绑定源进行数据绑定
-创建一个数据绑定源对象,并指定相应的数据源。
- 将数据绑定源绑定到DataGridView的数据源属性上。
5.自定义数据绑定
如果以上方法无法满足需求,还可以使用自定义数据绑定方法。
自定义数据绑定通常涉及以下几个方面:
- 创建一个数据源类,实现数据源接口,如IList、IBindingList或ICollectionView。
- 创建一个继承自DataGridView的自定义控件。
.NET4.0 通过代码添加控件

4.0 通过代码添加控件
GridView类是所有GridView控件的抽象,其可以用于创建GridView控件,也可以通过该类的字段和属性对GridView控件进行预定义,或通过该类的方法对控件进行操作。
之前介绍的使用代码创建GridView控件,事实上就是实例化了一个GridView类的对象。
1.在窗体页中添加代码
先在窗体中,添加GridView控件。
然后,在控件中,添加数据表字段内容。
同
2.构造GridView对象
双击Default.aspx.cs文件,并在代码中构造一个GridView控件对象,使用
3.添加GridView事件
用户除了在代码文件中,添加GridView控件对象以外,还可以添加一些对数据进行的操作事件。
例如,编辑数据、删除数据、选择数据记录等,正如在Default.aspx 窗体页中所添加的一些操作内容。
下面来看一下,Default.aspx.cs代码文件中,所有代码内容,并了解窗体页与代
通过GridView控件添加数据内容,可以在窗体页中显示数据表内容。
并且,用户还可以操作窗体页中的表格内容,以达到修改数据库中数据信息。
例如,单击工具栏中的【启动调试】按钮,即可在IE浏览器中显示数据库中数据表的数据信息,如图10-17所示。
图10-17 显示数据表内容
然后,用户可以单击第一条记录后面的【删除】链接,并弹出的“确定要删除吗?”信息,并单击【确定】按钮。
删除成功后,将提示“删除成功!”信息,否则提示“删除失败!”信息,如图10-18所示。
图10-18 删除记录。
课件:9-2 知识准备 - 9-2-9 GridView控件高级应用[4页]
![课件:9-2 知识准备 - 9-2-9 GridView控件高级应用[4页]](https://img.taocdn.com/s3/m/4a7a5f020975f46526d3e1db.png)
9.2.9 GridView控件高级应用GridView控件应用概述GridView控件在实际项目开发中应用很广,在上一章中我们已学习了GridView控件的初步使用方法,在这一节中我们进一步学习GridView控件的使用。
内容包括:•GridView以表格的形式显示数据•GridView控件的多个事件处理方法9.2.9 GridView控件高级应用GridView控件应用1、GridView以表格的形式显示数据(1)表格中的行与单元格GridViewRow类代表表格中的行,其RowType属性指定了行的类型,其值为DataControlRowType值之一。
RowType属性具体值见表。
行类型说明DataRow GridView控件中的一个数据行。
Footer GridView控件中的脚注行。
Header GridView控件中的表头行。
EmptyDataRow GridView控件中的空行。
当GridView控件中没有要显示的任何记录时,将显示空行。
Pager GridView控件中的一个页导航行。
Separator GridView控件中的一个分隔符行。
9.2.9 GridView控件高级应用GridView控件应用1、GridView以表格的形式显示数据(2)表格中的列GridView控件可以显示多种类型的表格列,具体如表所示:列字段类型说明BoundField以文本形式显示数据源中某个字段的值。
ButtonField 显示数据绑定控件中的命令按钮。
根据控件的不同,这允许您显示带有自定义按钮控件的行或列,如“添加”或“移除”按钮。
CheckBoxField 显示数据绑定控件中的复选框。
此数据控件字段类型通常用于显示带有布尔值的字段。
CommandField显示数据绑定控件中要执行编辑、插入或删除操作的内置命令按钮。
HyperLinkField将数据源中某个字段的值显示为超链接。
ImageField显示数据绑定控件中的图像。
【Winform-自定义控件】DataGridView多维表头

【Winform-⾃定义控件】DataGridView 多维表头[datagridview与treeview绑定]treeview代码:datagridview多维表头实现效果:⾃定义控件全部代码:DataTable dtable = new DataTable("Rock");//添加8列dtable.Columns.Add("1", typeof (System.String));dtable.Columns.Add("2", typeof (System.String));dtable.Columns.Add("3", typeof (System.String));dtable.Columns.Add("4", typeof (System.String));dtable.Columns.Add("5", typeof (System.String));dtable.Columns.Add("6", typeof (System.String));dtable.Columns.Add("7", typeof (System.String));dtable.Columns.Add("8", typeof (System.String));//添加⼀⾏数据DataRow drow = dtable.NewRow();drow["1"] = "11";drow["2"] = "22";drow["3"] = "33";drow["4"] = "44";drow["5"] = "55";drow["6"] = "66";drow["7"] = "77";drow["8"] = "88";dtable.Rows.Add(drow);//绑定数据multiColHeaderDgv2.DataSource = dtable;using System;using System.Collections.Generic;using System.Text;using System.Windows.Forms;using System.Drawing;using ponentModel;namespace myMultiColHeaderDgv{public class MultiColHeaderDgv:DataGridView{#region 字段定義/// <summary>多維列標題的樹結構////// </summary>private TreeView _ColHeaderTreeView;///<summary>樹的最⼤層數//////</summary>private int iNodeLevels;///<summary>⼀維列標題的⾼度//////</summary>private int iCellHeight;///<summary>所有葉節點//////</summary>private IList<TreeNode> ColLists = new List<TreeNode>();#endregion#region屬性定義///<summary>多維列標題的樹結構//////</summary>[Description("多維列標題的樹結構")]public TreeView myColHeaderTreeView{get { return _ColHeaderTreeView; }set { _ColHeaderTreeView = value; }}#endregion#region⽅法函數///<summary>遞歸計算樹最⼤層數,並保存所有葉節點//////</summary>///<param name="tnc"></param>///<returns></returns>private int myGetNodeLevels(TreeNodeCollection tnc){if (tnc == null) return0;foreach (TreeNode tn in tnc){if ((tn.Level + 1) > iNodeLevels)//tn.Level是從0開始的 {iNodeLevels = tn.Level+1;}if (tn.Nodes.Count > 0){myGetNodeLevels(tn.Nodes);}else{ColLists.Add(tn);//葉節點}}return iNodeLevels;}///<summary>調⽤遞歸求最⼤層數、列頭總⾼//////</summary>public void myNodeLevels(){iNodeLevels = 1;//初始為1ColLists.Clear();int iNodeDeep = myGetNodeLevels(_ColHeaderTreeView.Nodes);iCellHeight = this.ColumnHeadersHeight;this.ColumnHeadersHeight = this.ColumnHeadersHeight * iNodeDeep;//列頭總⾼=⼀維列⾼*層數 }///<summary>获得合并标题字段的宽度//////</summary>///<param name="node">字段节点</param>///<returns>字段宽度</returns>private int GetUnitHeaderWidth(TreeNode node){int uhWidth = 0;//获得最底层字段的宽度if (node.Nodes == null)return this.Columns[GetColumnListNodeIndex(node)].Width;if (node.Nodes.Count == 0)return this.Columns[GetColumnListNodeIndex(node)].Width;//获得⾮最底层字段的宽度for (int i = 0; i <= node.Nodes.Count - 1; i++){uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]);}return uhWidth;}///<summary>获得底层字段索引//////</summary>///' <param name="node">底层字段节点</param>///<returns>索引</returns>///<remarks></remarks>private int GetColumnListNodeIndex(TreeNode node){for (int i = 0; i <= ColLists.Count - 1; i++){if (ColLists[i].Equals(node))return i;}return -1;}///<summary>绘制合并表头//////</summary>///<param name="node">合并表头节点</param>///<param name="e">绘图参数集</param>///<param name="level">结点深度</param>///<remarks></remarks>public void PaintUnitHeader(TreeNode node,System.Windows.Forms.DataGridViewCellPaintingEventArgs e,int level){//根节点时退出递归调⽤if (level == 0)return;RectangleF uhRectangle;int uhWidth;SolidBrush gridBrush = new SolidBrush(this.GridColor);SolidBrush backColorBrush = new SolidBrush(e.CellStyle.BackColor);Pen gridLinePen = new Pen(gridBrush);StringFormat textFormat = new StringFormat();textFormat.Alignment = StringAlignment.Center;uhWidth = GetUnitHeaderWidth(node);//与原贴算法有所区别在这。
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添加、删除和修改数据库中的内容作者:天涯来源:中国自学编程网发布日期:1214063638介绍一个数据控件DataGridView,它是 3.5中新增加的的重要控件。
它是一种网格形式的控件,能以表格的形式显示数据,它的优势是能多行显示数据,在数据库的操作中会经常用到。
(1)打开VS2008,在D:\C#\ch14目录下建立名为DataGridViewTest的Windows应用程序,打开工程,为当前窗体添加控件,如表14-2所示。
表14-2 添加控件列表控件名NameTextDataGridViewdataGridView1ButtonbtnRef更新设置ButtonbtnDelete删除(2)接下来需要设置DadaAdapter和DataSet,方法同上一节一样。
选中DataGridView的DataSource属性。
(3)单击“下一步”按钮,选择“数据连接”图标。
(4)最后一步需要选择数据库对象,本例是要操作StudentInf数据库中的表,所以选择“表”复选框。
(5)设置完毕后,整个程序界面就设置完了。
程序界面设计完毕后,接下来要做的工作就是通过修改dataGridView1中的数据来更新数据库中的内容。
它实现的原理很简单,通过studentInfDataSet把dataGridView1绑定到Class1表,studentInfDataSet处于中间位置,所以在dataGridView1中修改的数据必须要传递到studentInfDataSet后才能改变数据库中的内容。
(1)双击“更新设置”按钮,添加如下代码。
this.sqlDataAdapter1.Update(this.studentInfDataSet);该代码的功能是调用sqlDataAdapter1的Update()方法实现对studentInfDataSet的更新。
(2)按F5键,程序运行以后,对dataGridView1添加一行新的数据,然后单击“更新设置”按钮,完成后关闭程序再打开。
一个Winform下DataGridView控件外观的自定义类

⼀个Winform下DataGridView控件外观的⾃定义类⼀、关于起因最近⾮常频繁的使⽤DataGridView控件,VS提供的Winform下DataGridView的默认样式⾮常难看。
如果做美化处理的话,需要调整的地⽅⾮常多,且该控件的很多设置属性⾮常的晦涩,不是很⼈性化。
每次进⾏设置都煞费脑筋,并且需要设置的DataGridView控件⼜⽐较多,如果⼿⼯⼀个⼀个调整⾮常⿇烦。
如果在每个窗体⾥逐个⼀⾏⼀⾏的⽤代码来设置,会造成代码很凌乱、琐碎,因此我对DataGridView格式设置的常⽤项封装到⼀个Helper类,通过这个帮助类可以⼀步到位完成设置。
对DataGridView控件,我需要完成的⼀些基本的格式控制,包括以下⼀些内容:1、标题⾏背景⾊、前景⾊、字体设置、平⾯化样式、⾏⾼2、标题列宽度,平⾯化样式3、偶数⾏背景⾊、前景⾊4、奇数⾏背景⾊、前景⾊5、数据⾏⾼度、字体6、列宽度,对齐⽅式7、禁⽌编辑、添加、删除、调整⾏⾼、列宽、排序8、去除控件外边框最终处理过后的风格类似如下图所⽰⼆、CGridHelper类模块的调⽤最终我所希望的实现格式化DataGridView控件的形式是通过⼀⾏代码来实现,类似如下所⽰:1Dim mGridHelper As New CGridHelper(GridVersion, Color.FromArgb(250, 250, 250),2New Font("微软雅⿊", 10), 30, Color.FromArgb(159, 210, 235), Color.FromArgb(0, 0, 0), 24,3New Font("微软雅⿊", 9), 30, Color.FromArgb(250, 250, 250), Color.FromArgb(225, 225, 225), Color.FromArgb(0, 0, 0),4"0;80;70;595", "M;M;M;L")其中列宽的控制通过⼀个字符串来设置,⽤分号来分隔数字,各数字依次设置对应列的宽度;列的对齐⽅式也类似,不过左、中、右分别⽤字母L/M/R表⽰。
如何在DataGridView中加入自定义组件

如何在DataGridView中加入自定义组件我想在DataGridView编辑时显示如下图控件:(1)创建一个自定义组件UserControl,并继承IDataGridViewEditingControl接口(用意:在DataGridView进入编辑状态时可以调用该控件),添加如下代码:using System;using System.Collections.Generic;using ponentModel;using System.Drawing;using System.Data;using System.Text;using System.Windows.Forms;namespace Class.baseSys.controlSys{public partial class UserControl1 : UserControl, IDataGridViewEditingControl{int rowIndex;DataGridView dataGridView;private bool valueChanged = false;public UserControl1(){InitializeComponent();}/// <summary>/// 更改控件的用户界面(UI),使之与指定单元格样式一致。
/// </summary>/// <param name="dataGridViewCellStyle">要用作用户界面的模型的System.Windows.Forms.DataGridViewCellStyle。
</param>public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle){this.Font = dataGridViewCellStyle.Font;this.textBox1.ForeColor = dataGridViewCellStyle.ForeColor;this.textBox1.BackColor = dataGridViewCellStyle.BackColor;}/// <summary>/// 确定指定的键是应由编辑控件处理的常规输入键,还是应由System.Windows.Forms.DataGridView 处理的特殊键。
DataGridView控件的使用(收集)

新的 DataGridView 是 .NET 2.0 中的一个新控件,是针对 .NET 1.x 中功能较差的标准 DataGrid 控件而设计的。
Matthew MacDonald 在本文中论述了许多改进,包括:DataGridView 支持大量自定义和细致的格式设置、灵活的大小调整和选择、更好的性能以及更丰富的事件模型。
.NET Framework 的前两个版本(.NET 1.0 和 .NET 1.1)在数据绑定方面留下了明显的空白。
尽管开发人员拥有一个灵活的可配置模型,可以将几乎所有的控件链接到几乎所有的数据源,但却没有一种有效的方法来显示完整的信息表。
可以实现此目的的唯一工具就是 DataGrid 控件,这种控件非常适合于处理简单的演示,但是不太适合实际代码。
填补这项空白是 .NET 2.0 的主要目标之一,并且 Microsoft 已经用全新的网格控件 DataGridView 来实现此目标。
DataGridView 有两个指导原则。
首先,其目标是支持常见任务(如主控/详细列表、验证和数据格式设置),而不需要您编写许多代码。
更重要的是,设计过程中始终考虑了扩展性,因此您可以集成所需的专用功能,而不必采用低级别的复杂编程。
本页内容基本数据绑定美化 DataGridView使用 DataGridView 选择单元格DataGridView 对象DataGridView 样式自定义单元格格式按钮列图像列编辑 DataGridView处理错误验证输入使用列表列约束选择小结基本数据绑定熟悉 DataGridView 的最佳方法就是实际尝试一下,无需配置任何属性。
就像 DataGrid 一样,您可以使用 DataSource 属性来绑定 DataTable 对象(或从 DataTable 派生的对象)。
Dim ds As DataSet = GetDataSet()DataGridView1.DataSource = ds.Tables(‖Customers‖)与 DataGrid 不同的是,DataGridView 一次只能显示一个表。
datagridview控件用法

datagridview控件用法
1、将datagridview控件添加到From:添加DataGridView控件,双击界面上的DataGridView,根据实际情况在设计界面里调整控件大小,在属性框中设置DataGridView的数据源(DataSource)的值。
2、定义控件的列:右键DataGridView,选择“属性”,然后在弹出的对话框中,将“列集合”条目选中,点击“...”,此时可以定义你想要的列,设置列名、数据类型、宽度等信息。
3、绑定数据源:当定义好DataGridView的列后,为了显示该出来的具体的数据,可以将DataGridView与真实的数据源绑定,即可在DataGridView中显示具体数据,可以在设计时通过Visual Studio的Data Sources应用程序,或者在窗体上加载DataGridView控件时,通过代码来实现。
4、DataGridView添加行或者删除行:可以使用DataGridView的Rows属性来添加新行,或者通过使用RemoveAt(int index)方法来删除列中指定行。
5、DataGridView编辑功能及事件:默认情况下DataGridView中支持修改单元格数据,可以设置DataGridView的ReadOnly属性为false使其允许进行修改,并且DataGridView中TextBox派生的控件中的CellValidating事件、
CellValueChanged事件等都可以响应DataGridView的编辑功能,可以在这些事件中实现对数据的监测或者保存数据的操作。
datagridview 用法

datagridview 用法DataGridView是Windows Forms中的控件,是一种可以显示数据的表格控件。
常用的DataGridView属性和方法:1. 属性:DataSource:设置或获取数据源。
2. 属性:AutoGenerateColumns:设置或获取是否自动生成列。
3. 属性:RowHeadersVisible:设置或获取是否显示行标题。
4. 方法:Refresh:刷新DataGridView控件的显示。
常用的DataGridView事件:1. 事件:RowValidating:当行数据验证时发生。
2. 事件:CellClick:单击单元格时发生。
3. 事件:CellDoubleClick:双击单元格时发生。
4. 事件:SelectionChanged:当选择项发生更改时发生。
DataGridView的使用步骤:1. 创建DataGridView实例。
2. 设置DataSource属性。
3. 可选设置AutoGenerateColumns属性。
4. 可选设置RowHeadersVisible属性及其他属性。
5. 注册事件处理程序。
6. 添加DataGridView到窗体中。
下面是一个简单示例代码:C#代码:csharpdataGridView1.DataSource = dataTable; dataTable为绑定数据源dataGridView1.AutoGenerateColumns = true;dataGridView1.RowHeadersVisible = false;dataGridView1.CellClick += DataGridView_CellClick;注:DataGridView_CellClick是事件处理程序的方法名,需要自行定义。
DataGridView控件用法(可能不是很全面,因为这是自己常常用到的一些小总结):

DataGridView控件⽤法(可能不是很全⾯,因为这是⾃⼰常常⽤到的⼀些⼩总结):⼀、DataGridView属性设置1、我们单击选中⾏的时候,默认是选择⼀个单元格,不能选择⼀整⾏,我们只需设置DataGridView的属性SelectionMode为FullRowSelect 。
⽤代码表⽰:this.dataGridView1.SelectionMode =DataGridViewSelectionMode.FullRowSelect;2、选择多⾏,可设置DataGridView的属性MultiSelect为false 。
⽤代码表⽰:this.dataGridView1.MultiSelect = false;这样就使DataGridView不能够选择多⾏,只能选择⼀⾏了3、是否⾃动创列:dataGridView1.AutoGenerateColumns = false;4、DataGridView这个控件会默认的在第⼀⾏第⼀列选中。
这个问题我在⽹上看到了很多回答,也有很多⼈问。
可能是我⽤的⽅法不对,效果不是很好后来找到了这种答案: dataGridView1.ClearSelection();⼀⾏就可以。
5、设置标题样式&字体:⾸先把这个“EnableHeadersVisualStyles”属性设置为false。
在然后设置标题的样式,设置这个属性“ColumnHeadersDefaultCellStyle”:6、设置⾏的样式,设置DefaultCellStyle属性:1、单击项或双击⾏时,获取⾏的数据(CellClick)1private void DGV_CellClick(object sender, DataGridViewCellEventArgs e)2 {34if (e.RowIndex != -1)//判断是否点在⾏上5 {6 txt_No.Text = this.DGV["Col_No", e.RowIndex].Value.ToString();7 txt_Name.Text = this.DGV["Col_Name", e.RowIndex].Value.ToString();8 txt_Type.Text = this.DGV["Col_Type", e.RowIndex].Value.ToString();9 txt_Time.Text = this.DGV["Col_Time", e.RowIndex].Value.ToString();10 }11 }View Code“Col_No”。
winform datagridview控件用法

winform datagridview控件用法Winform DataGridView 控件用法详解一、简介Winform DataGridView 控件是 .NET Framework 中提供的一个强大的数据显示和编辑控件。
它可以显示和编辑多种类型的数据(如文本、数字、日期、图像等),并且提供了丰富的功能和灵活的样式设置,可以方便地实现数据的展示、排序、筛选、编辑、分页等操作。
二、绑定数据源1. 绑定数据集可以通过设置DataGridView 的DataSource 属性来绑定一个数据集(DataSet)或数据表(DataTable)。
在Visual Studio 的设计器中,通过选择数据源和数据成员来实现绑定,也可以通过代码实现。
例如:dataGridView1.DataSource = dataSet.Tables["TableName"];2. 绑定数据集合除了绑定数据集,还可以绑定数据集合(如List<T>、BindingList<T> 等)。
在数据集合发生变化时,DataGridView 会自动更新显示的数据。
例如:List<User> userList = new List<User>();dataGridView1.DataSource = userList;3. 动态绑定数据绑定数据源后,可以通过设置DataGridView 的AutoGenerateColumns 属性为true,自动根据数据源的结构创建列。
也可以通过手动添加列来控制显示的列数和顺序。
例如:dataGridView1.AutoGenerateColumns = true;三、设置列样式1. 自动调整列宽可以通过设置DataGridView 的AutoSizeColumnsMode 属性来调整列宽。
通常选择AllCells 或Fill,前者会根据列中的内容调整列宽,后者会填充整个控件。
怎样用自定义控件编辑DataGridView(WinForm)单元格的值

怎样用自定义控件编辑DataGridView(WinForm)单元格的值控件提供了多种列类型,使得用户可以通过多种方式输入和编辑值。
但是,如果这些列类型无法满足数据输入要求,您也可以使用承载所选控件的单元格创建自己的列类型。
要做到这一点,必须定义派生自DataGridViewColumn 和DataGridViewCell 的类。
您还必须定义派生自 Control并实现 IDataGridViewEditingControl 接口的类。
下面的代码示例演示如何创建日历列。
此列的单元格在普通的文本框单元格中显示日期,但当用户编辑单元格时,就会出现DateTimePicker 控件。
为了避免必须再次实现文本框显示功能,CalendarCell 类从DataGridViewTextBoxCell 类派生,而不是直接从 DataGridViewCell 类继承。
注意当从DataGridViewCell 或DataGridViewColumn 派生并向派生类添加新属性时,请确保重写Clone 方法以便在克隆操作期间复制新属性。
还应调用基类的 Clone 方法,以便将基类的属性复制到新的单元格或列中。
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 forthe 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, objectinitialFormattedValue, DataGridViewCellStyledataGridViewCellStyle){// 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 theediting 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 timeas 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 the IDataGridViewEditingControl.EditingControlFormattedValue// property.public object EditingControlFormattedValue{get{return this.Value.T oShortDateString();}set{String newValue = value as String;if (newValue != null){this.Value =DateTime.Parse(newValue);}}}// Implements the//IDataGridViewEditingControl.GetEditingControlFormattedVa luemethod.public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context){return EditingControlFormattedValue;}// Implements the//IDataGridViewEditingControl.ApplyCellStyleToEditingContro l method.public void ApplyCellStyleT oEditingControl(DataGridViewCellStyle dataGridViewCellStyle){this.Font = dataGridViewCellStyle.Font;this.CalendarForeColor = dataGridViewCellStyle.ForeColor;this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;}// Implements the IDataGridViewEditingControl.EditingControlRowIndex// property.public int EditingControlRowIndex{get{return rowIndex;}set{rowIndex = value;}}// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey // method.public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey){// Let the DateTimePicker handle thekeys 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 the IDataGridViewEditingControl.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 thecontents of the cell// have changed.valueChanged = true;this.EditingControlDataGridView.NotifyCurrentCellDirty(true );base.OnValueChanged(eventargs);}}public class Form1 : Form{private DataGridView dataGridView1 = newDataGridView();[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 inthis.dataGridView1.Rows){row.Cells[0].Value = DateTime.Now;}}}。
datagridview控件用法

datagridview控件用法DataGridView控件是Windows Forms中最常用的控件之一,它可以用于显示和编辑数据。
在本文中,我们将介绍DataGridView控件的用法,包括如何绑定数据、设置列、样式和事件处理等。
1. 绑定数据DataGridView控件可以绑定各种数据源,包括DataTable、DataSet、BindingSource等。
绑定数据的方法有两种:一种是在设计时通过属性窗口设置,另一种是在运行时通过代码设置。
在设计时,我们可以通过以下步骤绑定数据:1)将DataGridView控件拖放到窗体上;2)在属性窗口中选择DataSource属性,然后选择要绑定的数据源;3)选择DataMember属性,然后选择要显示的数据表或数据集。
在运行时,我们可以通过以下代码绑定数据:dataGridView1.DataSource = dataTable;其中,dataTable是一个DataTable对象,它包含要显示的数据。
2. 设置列DataGridView控件可以显示多列数据,我们可以通过以下方法设置列:1)在设计时,通过列编辑器添加列;2)在运行时,通过代码添加列。
在设计时,我们可以通过以下步骤添加列:1)在属性窗口中选择Columns属性,然后点击“…”按钮;2)在列编辑器中添加列,设置列的属性,如HeaderText、DataPropertyName、Width等。
在运行时,我们可以通过以下代码添加列:DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();column.HeaderText = "Column1";column.DataPropertyName = "Column1";column.Width = 100;dataGridView1.Columns.Add(column);其中,DataGridViewTextBoxColumn是一个列类型,它表示文本列。
datagridview在vbnet中的操作技巧

DataGridView在中的操作技巧目录:1、取得或者修改当前单元格的内容2、设定单元格只读3、不显示最下面的新行4、判断新增行5、行的用户删除操作的自定义6、行、列的隐藏和删除7、禁止列或者行的Resize8、列宽和行高以及列头的高度和行头的宽度的自动调整9、冻结列或行10、列顺序的调整11、行头列头的单元格12、剪切板的操作13、单元格的ToolTip的设置14、右键菜单(ContextMenuStrip)的设置15、单元格的边框、网格线样式的设定16、单元格表示值的设定17、用户输入时,单元格输入值的设定18、设定新加行的默认值1、DataGridView 取得或者修改当前单元格的内容:当前单元格指的是DataGridView 焦点所在的单元格,它可以通过DataGridView 对象的CurrentCell 属性取得。
如果当前单元格不存在的时候,返回Nothing(C#是null)[]' 取得当前单元格内容MessageBox.Show(DataGridView1.CurrentCell.Value)' 取得当前单元格的列IndexMessageBox.Show(DataGridView1.CurrentCell.ColumnIndex)' 取得当前单元格的行IndexMessageBox.Show(DataGridView1.CurrentCell.RowIndex)另外,使用DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 和列:DataGridView.CurrentCellAddress.X 。
这对于避免取消共享行的共享非常有用。
当前的单元格可以通过设定DataGridView 对象的CurrentCell 来改变。
可以通过CurrentCell 来设定DataGridView 的激活单元格。
datagrid控件的用法

datagrid控件的用法摘要:I.引言- 介绍datagrid 控件- 阐述其在数据展示和操作中的作用II.datagrid 控件的基本用法- 创建datagrid 控件- 设置datagrid 控件的属性- 绑定数据源III.datagrid 控件的高级用法- 数据分页- 数据筛选和排序- 数据编辑和删除IV.常见问题及解决方案- 数据重复显示问题- 数据无法编辑问题- 删除数据时出现错误问题V.总结- 回顾datagrid 控件的主要功能- 强调其在数据展示和操作中的重要性正文:I.引言DataGrid 控件是一种常用的数据展示和操作控件,它可以在Windows 窗体应用程序和Web 应用程序中使用。
通过使用DataGrid 控件,我们可以轻松地显示大量数据,并允许用户对数据进行编辑、删除等操作。
在本文中,我们将介绍DataGrid 控件的用法,包括基本用法和高级用法,并探讨一些常见问题及解决方案。
II.datagrid 控件的基本用法A.创建datagrid 控件在Visual Studio 中,我们可以通过以下步骤创建一个DataGrid 控件:1.在工具箱中找到DataGrid 控件,并将其拖放到窗体或aspx 页面上。
2.调整DataGrid 控件的大小和位置。
B.设置datagrid 控件的属性DataGrid 控件具有许多属性,如数据源、绑定方式、分页等。
我们可以通过设置这些属性来定制DataGrid 控件的行为。
C.绑定数据源要将数据绑定到DataGrid控件,我们需要设置DataGrid控件的数据源属性。
数据源可以是数据表、数据视图或其他数据源。
例如,在C#中,我们可以使用以下代码将DataGrid控件绑定到数据表:```csharpdataGrid.DataSource = dataTable;```III.datagrid 控件的高级用法A.数据分页当数据量较大时,我们需要对数据进行分页,以提高用户体验。
winform datagridview 用法

winform datagridview 用法
WinForm中的DataGridView是一个非常强大的控件,它可以展示和编辑数据,还可以支持排序、筛选和分页等功能。
以下是DataGridView的使用方法:
1. 添加DataGridView控件到窗体中。
2. 设置DataGridView的数据源,可以是列表、数组或DataTable等。
3. 设计DataGridView的列,包括列的宽度、显示名称、数据类型等。
4. 配置DataGridView的显示属性,如是否允许排序、是否显示分页等。
5. 编写代码来填充和操作DataGridView的数据源,如添加、删除、编辑等。
6. 处理DataGridView的事件,如单元格点击、选中行改变等。
7. 为DataGridView添加自定义控件,如复选框、下拉框等。
8. 对DataGridView进行格式化,如日期格式化、货币格式化等。
9. 添加DataGridView的上下文菜单,为用户提供更多的操作选项。
以上是WinForm中DataGridView的基本用法,希望对大家有所帮助。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
.NET新手指南:轻松自定义DataGridView控件
.NET DataGridView是一个便于使用的数据绑定控件。
本文为.NET新手介绍了如何使用.NET配置向导VB Express自定义DataGridView控件。
只需非常简单的修改以及一两行代码,便可以轻松实现交替颜色行,自定义排序功能以及显示编辑行。
这样一个既可以浏览数据又可以编辑数据的窗体非常实用。
本文的目标读者是.NET新手。
首先讲述如何创建一个新连接,然后讲述如何自定义结果控件,使用Visual Basic Express(VB Express)配置向导,本文将描述如何填充DataGridView控件,然后按照以下步骤进行提高:
1、行的显示颜色交替,构成一个绿色条效果;
2、禁用掉DataGridView内置的单列排序功能;
3、执行这个窗体时显示编辑行。
开始
VB Express提供了许多方法检索和操作外部数据,例如,只需要运行VB Express的配置向导就可以建立一个到MS Access 示例数据库Northwind.mdb中Customers的连接:
1、启动VB Express,然后在标准工具栏上点击新建项目按钮,在弹出的对话框中选择Windows Form Application;
2、在名称控件处输入一个有意义的名字,点击确定按钮;
3、点击解决方案资源管理器右下角的数据源标签,如果没有看到这个标签,从“数据”菜单中选择显示数据源即可;
4、点击新建数据源按钮,启动新建数据源配置向导;
5、点击下一步,数据库选项保持默认设置;
6、在下一个面板中点击新建连接;
7、在弹出的新建连接对话框中,点击修改,从弹出的修改数据源对话框中选择Access数据库文件,然后点击确定按钮;
8、在新建连接对话框中点击浏览,找到Northwind.mdb的位置(在Office目录的Samples文件夹下),然后点击确定按钮;
9、点击测试连接,然后点击确定按钮清除确认消息;
10、如果连接工作正常,点击确定返回向导窗口,然后点击下一步继续;
11、VB Express会询问你是否要拷贝数据库,如果你选择“是”,将会把整个数据库拷贝到你的项目下,在这个例子中,我们选择“否”;
12、接下来的面板中让你将配置信息保存到配置文件中,默认是要保存,点击下一步即可(向导会检索数据库对象,并在源文件中显示它们,在这里你可以识别一下将要在.Net项目中检索和操作的数据);
13、点击“+”号展开表节点,选中Customers表,保留默认的NorthwindDataSet,VB Express的数据集;
14、点击完成,VB Express将会检索指定的数据。
创建好连接后,还需要一个窗体来显示数据,请跟着我做:
1、点击数据源标签;
2、点击Form1标签,然后从数据源标签拖动Customers数据集到窗体设计器中的Form1上,VB Express将会产生一个DataGridView控件并自动命名,图1显示了结果窗体和窗体设计器中的网格。
窗体和窗体设计器中的网格:配置向导创建的可以显示数据的控件
3、从文件菜单中选择保存所有,然后点击保存按钮。
至此,你已经有一个来自Northwind数据库的数据集,和一个显示该数据的DataGridView控件及控件所在的窗体,所有需要做的就是运行一下向导。
行显示颜色交替
第一个增强是,使用向导创建的控件可以通过修改行的颜色提高易读性,使用DataGridView时,可以很容易修改属性:
1、在窗体设计器中,选择DataGridView控件(不要双击,将会打开窗体的代码页);
2、在属性窗口中,打开AlternatingRowsDefaultCellStyle属性;
3、点击BackColor属性的下拉箭头,显示CellStyleBuilder对话框;
4、选择一个与当前颜色不同的颜色(默认是白色),在这个例子中,选择蓝色,如图2所示,然后点击确定按钮。
CellStyleBuilder对话框:选择一个交替的行颜色
5、按F5运行程序,图3显示了使用交替颜色填充的网格控件。
填充好的网格控件:行的颜色在蓝色和白色间交替使用
记住,只设置交替的一行的属性颜色就可以了,不是要设置所有行的属性,如果还想更多一点变化,相应设置BackColor和ForeColor即可。
控制排序顺序
最初,你产生的控件是按表的顺序填充的,因为还没有指定排序顺序,然而,DataGridView是天生就支持排序的,只需要点击标题栏,控件就会以该栏升序排序记录,再点击一次就按降序排序,对于大多数控件而言,在填充控件时你都可以排序数据:
1、在窗体设计器中,选择CustomersBindingSource组件,将会在相应的属性窗口中更新其项目;
2、在窗口的底部,找到sort属性,输入city,如图4所示。
找到Sort,输入City:指定一个排序列
3、按F5运行程序,正如你在图5中所看到的,控件按照City值以升序排序记录。
如果想降序排列的话,只需要加上DESC关键词就可以了,即输入City DESC。
控件排序记录:窗体通过City值排序记录
你可能会禁止这个原生态的排序功能,但你需要为每个禁止排序的列编写一小段代码,例如,为了禁止Contact Title列的排序功能,请跟着我做:
1、在设计视图窗体中,从视图菜单选择代码,或按F7;
2、开始输入代码,很快你就会发现智能感应不会显示控件包含的列名,相反,它是按照位置显示列名的,这不是引用列的最佳办法;
3、为了修改DataGridView控件的列的默认名称,必须修改控件本身的Columns集合,在设计视图中,双击网格(不是窗体),你可能需要稍微放大一下窗体,以便准确选中一个网格,当属性标题显示CustomersDataGridView 时,你就可以确定选中的是网格而不是窗体了;
4、定位Columns集合,然后点击Builder按钮,启动编辑列对话框,如图6所示。
点击Builder按钮:查看网格的Columns集合
5、在选择列控件中,选择ContactTitle;
6、在设计区域(右下角),这个控件的Name属性值是DataGridViewTextBoxColumn4,使用一个更有意义的名字替代它,这里我们输入DataGridViewTextBoxContactTitle,如图7所示。
对那些不想设置的隐形列,将其Visible 属性设置为false即可。
为Name属性输入一个有意义的名称
7、点击确定返回代码窗口(Form1.vb);
8、输入下面的代码:
1.Me.DataGridViewTextBoxContactTitle.SortMode = DataGridViewColumnSo
rtMode.NotSortable
这一次智能感应按名称而不是位置列出了列,如图8所示。
智能感应按名称列出了列:使用列名代替位置号
9、保存所做的修改;
10、按F5执行项目,在结果窗体中,点击ContactTitle的标题栏,这一次窗体不会排序记录了,这是因为输入的代码禁用了排序功能。
显示编辑行
目前,示例窗体显示了91条记录,此时如果用户想要插入一行记录,必须滚动窗体到编辑行,你可以通过编程让窗体自动显示编辑行,将下面的代码添加到窗体的Load事件中,如图9所示。
1.Me.CustomersDataGridView.FirstDisplayedScrollingRowIndex = Custome
rsDataGridView.Rows.Count - 1
在窗体的Load事件中添加代码:强制窗体在载入时显示编辑行
按F5运行这个窗体,正如你在图10中所看到的,这个窗体显示了一些记录和编辑行。
显示记录和编辑行的窗体:现在启动窗体,可以看到显示了编辑行这个语句从行数量减去一个1,这样可以防止异常发生,因为编辑行没有真正的索引,直到你点击了它,即使它影响了行的数量。
这个方法仅仅是确保最后一行是可见的,所有的记录仍然是可用的,现在窗体显示的记录条数与其容量紧密相关,代码不需要做任何修改。
通过禁用编辑行,这样就将窗体改为浏览窗体了,不能再插入新的行了,要禁用编辑行,只需要在窗体的Load 事件中添加一句:
1.DataGridView1.AllowUserToAddRows = False
将AllowUserToAddRows属性设置True就启用编辑行。
自定义控件使其更易用和灵活
自定义示例窗体并不需要花多少时间:
1、只需要简单的修改就可以实现交替颜色行;
2、只需要一行代码就可以禁用掉内置的排序功能;
3、只需要一行代码就可以显示编辑行。
如果你是从Access或SQL Server转过来的,当你见识了可以创建和实现一个既可以浏览数据又可以编辑数据的窗体时,你一定会感到满意。
原文:The .NET Newbie's Guide to Customizing the DataGridView Control。