搜档网
当前位置:搜档网 › datagridview控件使用方法

datagridview控件使用方法

datagridview控件使用方法
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);

方法二比方法一要复杂一些,但是在一些特殊场合非常实用,例如,要在新行中的某些单元格添加下拉框、按钮之类的控件时,该方法很有帮助。DataGridViewRow row = new DataGridViewRow();是创建DataGridView的行对象,DataGridViewTextBoxCell是单元格的内容是个TextBox,DataGridViewComboBoxCell是单元格的内容是下拉列表框,同理可知,DataGridViewButtonCell

是单元格的内容是个按钮,等等。textboxcell是新创建的单元格的对象,可以为该对象添加其属性。然后通过row.Cells.Add(textboxcell)为row对象添加textboxcell单元格。要添加其他的单元格,用同样的方法即可。最后通过dataGridView1.Rows.Add(row)为dataGridView1控件添加新的行row。

DataGridView取得或者修改当前单元格的内容:

当前单元格指的是DataGridView 焦点所在的单元格,它可以通过DataGridView 对象的CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null)

// 取得当前单元格内容

Console.WriteLine(DataGridView1.CurrentCell.Value);

// 取得当前单元格的列Index

Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);

// 取得当前单元格的行Index

Console.WriteLine(DataGridView1.CurrentCell.RowIndex);

另外,使用DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y

列:DataGridView.CurrentCellAddress.X 。这对于避免取消共享行的共享非常有用。

当前的单元格可以通过设定DataGridView 对象的CurrentCell 来改变。可以通过CurrentCell 来设定DataGridView 的激活单元格。将CurrentCell 设为Nothing(null) 可以取消激活的单元格。

// 设定(0, 0) 为当前单元格

DataGridView1.CurrentCell = DataGridView1[0, 0];

在整行选中模式开启时,你也可以通过CurrentCell 来设定选定行。

/// 向下遍历

private void button4_Click(object sender, EventArgs e)

...{

int row = this.dataGridView1.CurrentRow.Index + 1;

if (row > this.dataGridView1.RowCount - 1)

row = 0;

this.dataGridView1.CurrentCell = this.dataGridView1[0, row];

}

/// 向上遍历

private void button5_Click(object sender, EventArgs e)

...{

int row = this.dataGridView1.CurrentRow.Index - 1;

if (row < 0)

row = this.dataGridView1.RowCount - 1;

this.dataGridView1.CurrentCell = this.dataGridView1[0, row];

}

* 注意: this.dataGridView 的索引器的参数是: columnIndex, rowIndex 或是columnName, rowIndex

这与习惯不同。

DataGridView设定单元格只读:

1)使用ReadOnly 属性

如果希望,DataGridView 内所有单元格都不可编辑,那么只要:

// 设置DataGridView1 为只读

DataGridView1.ReadOnly = true;此时,用户的新增行操作和删除行操作也被屏蔽了。

如果希望,DataGridView 内某个单元格不可编辑,那么只要:

// 设置DataGridView1 的第2列整列单元格为只读

DataGridView1.Columns[1].ReadOnly = true;

// 设置DataGridView1 的第3行整行单元格为只读

DataGridView1.Rows[2].ReadOnly = true;

// 设置DataGridView1 的[0,0]单元格为只读

DataGridView1[0, 0].ReadOnly = true;

2)使用EditMode 属性

DataGridView.EditMode 属性被设置为DataGridViewEditMode.EditProgrammatically 时,用户就不能手动编辑单元格的内容了。但是可以通过程序,调用DataGridView.BeginEdit 方法,使单元格进入编辑模式进行编辑。

DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;

3)根据条件设定单元格的不可编辑状态

当一个一个的通过单元格坐标设定单元格ReadOnly 属性的方法太麻烦的时候,你可以通过CellBeginEdit 事件来取消单元格的编辑。

// CellBeginEdit 事件处理方法

private void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)

{

DataGridView dgv = (DataGridView)sender;

//是否可以进行编辑的条件检查

if (dgv.Columns[e.ColumnIndex].Name == "Column1" && !(bool)dgv["Column2",

e.RowIndex].Value)

{

// 取消编辑

e.Cancel = true;

}

}

DataGridView不显示最下面的新行:

通常DataGridView 的最下面一行是用户新追加的行(行头显示* )。如果不想让用户新追加行即不想显示该新行,可以将DataGridView 对象的AllowUserToAddRows 属性设置为False。

// 设置用户不能手动给DataGridView1 添加新行

DataGridView1.AllowUserToAddRows = false;

但是,可以通过程序:DataGridViewRowCollection.Add 为DataGridView 追加新行。

补足:如果DataGridView 的DataSource 绑定的是DataView, 还可以通过设置

DataView.AllowAdd

属性为False 来达到同样的效果。

DataGridView判断新增行:

DataGridView 的AllowUserToAddRows属性为True时也就是允许用户追加新行的场合下,

DataGridView的最后一行就是新追加的行(*行)。

使用DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过DataGridView.NewRowIndex 可以获取新行的行序列号.

在没有新行的时候,NewRowIndex = -1。

DataGridView行的用户删除操作的自定义:

1)无条件的限制行删除操作。

默认时,DataGridView 是允许用户进行行的删除操作的。如果设置DataGridView对象的AllowUserToDeleteRows属性为False 时,用户的行删除操作就被禁止了。

// 禁止DataGridView1的行删除操作。

DataGridView1.AllowUserToDeleteRows = false;

但是,通过DataGridViewRowCollection.Remove 还是可以进行行的删除。

补足:如果DataGridView 绑定的是DataView 的话,通过DataView.AllowDelete 也可以控制行的删除。

2)行删除时的条件判断处理。

用户在删除行的时候,将会引发https://www.sodocs.net/doc/8d2160488.html,erDeletingRow 事件。在这个事件里,可以判断条件并取消删除操作。

// DataGridView1 的UserDeletingRow 事件

private void DataGridView1_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e)

{

// 删除前的用户确认。

if (MessageBox.Show("确认要删除该行数据吗?", "删除确认",

MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)

{

// 如果不是OK,则取消。

e.Cancel = true;

}

}

DataGridView行、列的隐藏和删除:

1)行、列的隐藏

// DataGridView1的第一列隐藏

DataGridView1.Columns[0].Visible = false;

// DataGridView1的第一行隐藏

DataGridView1.Rows[0].Visible = false;

2)行头、列头的隐藏

// 列头隐藏

DataGridView1.ColumnHeadersVisible = false;

// 行头隐藏

DataGridView1.RowHeadersVisible = false;

3)行和列的删除

' 删除名为"Column1"的列

DataGridView1.Columns.Remove("Column1");

' 删除第一列

DataGridView1.Columns.RemoveAt(0);

' 删除第一行

DataGridView1.Rows.RemoveAt(0);

4)删除选中行

foreach (DataGridViewRow r in DataGridView1.SelectedRows)

{

if (!r.IsNewRow)

{

DataGridView1.Rows.Remove(r);

}

}

DataGridView禁止列或者行的Resize:

1)禁止所有的列或者行的Resize

// 禁止用户改变DataGridView1的所有列的列宽

DataGridView1.AllowUserToResizeColumns = false;

//禁止用户改变DataGridView1の所有行的行高

DataGridView1.AllowUserToResizeRows = false;

但是可以通过DataGridViewColumn.Width 或者DataGridViewRow.Height 属性设定列宽和行高。

2)禁止指定行或者列的Resize

// 禁止用户改变DataGridView1的第一列的列宽

DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;

// 禁止用户改变DataGridView1的第一列的行宽

DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;

关于NoSet :

当Resizable 属性设为DataGridViewTriState.NotSet 时,实际上会默认以DataGridView 的

AllowUserToResizeColumns和AllowUserToResizeRows 的属性值进行设定。

比如:DataGridView.AllowUserToResizeColumns = False 且Resizable 是NoSet 设定时,Resizable = False 。

判断Resizable 是否是继承设定了DataGridView 的AllowUserToResizeColumns 和AllowUserToResizeRows 的属性值,

可以根据State 属性判断。如果State 属性含有ResizableSet,那么说明没有继承设定。

3)列宽和行高的最小值的设定

// 第一列的最小列宽设定为100

DataGridView1.Columns[0].MinimumWidth = 100;

// 第一行的最小行高设定为50

DataGridView1.Rows[0].MinimumHeight = 50;

4) 禁止用户改变行头的宽度以及列头的高度

// 禁止用户改变列头的高度

DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

// 设置用户改变行头的宽度

DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;

DataGridView列宽和行高自动调整的设定:

1) 设定行高和列宽自动调整

// 设定包括Header和所有单元格的列宽自动调整

DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

// 设定包括Header和所有单元格的行高自动调整

DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; AutoSizeColumnsMode 属性的设定值枚举请参照msdn 的DataGridViewAutoSizeRowsMode 说明。

2)指定列或行自动调整

// 第一列自动调整

DataGridView1.Columns[0].AutoSizeMode =

DataGridViewAutoSizeColumnMode.DisplayedCells;

AutoSizeMode 设定为NotSet 时,默认继承的是DataGridView.AutoSizeColumnsMode 属性。

3) 设定列头的高度和行头的宽度自动调整

// 设定列头的宽度可以自由调整

DataGridView1.ColumnHeadersHeightSizeMode =

DataGridViewColumnHeadersHeightSizeMode.AutoSize;

// 设定行头的宽度可以自由调整

DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

4)随时自动调整

a,临时的,让列宽自动调整,这和指定AutoSizeColumnsMode属性一样。

// 让DataGridView1 的所有列宽自动调整一下。

DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

// 让DataGridView1 的第一列的列宽自动调整一下。

DataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.AllCells);上面调用的AutoResizeColumns 和AutoResizeColumn

当指定的是DataGridViewAutoSizeColumnMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeColumn(0) 和DataGridView1.AutoResizeColumns()

b,临时的,让行高自动调整

// 让DataGridView1 的所有行高自动调整一下。

DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);

//让DataGridView1 的第一行的行高自动调整一下。

DataGridView1.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);上面调用的AutoResizeRows 和AutoResizeRow

当指定的是DataGridViewAutoSizeRowMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeRow (0) 和DataGridView1.AutoResizeRows()

c,临时的,让行头和列头自动调整

// 列头高度自动调整

DataGridView1.AutoResizeColumnHeadersHeight();

// 行头宽度自动调整

DataGridView1.AutoResizeRowHeadersWidth( DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

关于性能:

通过AutoSizeColumnsMode 或者AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,

尤其是在行和列数比较多的情况下。在这时用DisplayedCells 代替AllCells 能减少非所见的单元格的调整,从而提高性能。

DataGridView冻结列或行:

1)列冻结

DataGridViewColumn.Frozen 属性为True 时,该列左侧的所有列被固定,横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。

// DataGridView1的左侧2列固定

DataGridView1.Columns[1].Frozen = true;

但是,DataGridView.AllowUserToOrderColumns = True 时,固定列不能移动到非固定列,反之亦然。

2)行冻结

DataGridViewRow.Frozen 属性为True 时,该行上面的所有行被固定,纵向滚动时固定行不随滚动条滚动而上下移动。

// DataGridView1 的上3行固定

DataGridView1.Rows[2].Frozen = true;

DataGridView列顺序的调整:

设定DataGridView 的AllowUserToOrderColumns 为True 的时候,用户可以自由调整列的顺序。当用户改变列的顺序的时候,其本身的Index 不会改变,但是DisplayIndex 改变了。你也可以通过程序改变DisplayIndex 来改变列的顺序。列顺序发生改变时会引发ColumnDisplayIndexChanged 事件:

// DataGridView1的ColumnDisplayIndexChanged事件处理方法

private void DataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)

{

Console.WriteLine("{0} 的位置改变到{1} ",

https://www.sodocs.net/doc/8d2160488.html,, e.Column.DisplayIndex);

}

行头列头的单元格:

// 改变DataGridView1的第一列列头内容

DataGridView1.Columns[0].HeaderCell.Value = "第一列";

// 改变DataGridView1的第一行行头内容

DataGridView1.Rows[0].HeaderCell.Value = "第一行";

// 改变DataGridView1的左上头部单元内容

DataGridView1.TopLeftHeaderCell.Value = "左上";

另外你也可以通过HeaderText 来改变他们的内容。

[C#]

// 改变DataGridView1的第一列列头内容

DataGridView1.Columns[0].HeaderText = "第一列";

DataGridView剪切板的操作:

DataGridView.ClipboardCopyMode 属性被设定为DataGridViewClipboardCopyMode.Disable

以外的情况时,「Ctrl + C」按下的时候,被选择的单元格的内容会拷贝到系统剪切板内。格式有:Text,UnicodeText,Html,CommaSeparatedValue。可以直接粘贴到Excel 内。ClipboardCopyMode 还可以设定Header部分是否拷贝:EnableAlwaysIncludeHeaderText 拷贝Header部分、EnableWithoutHeaderText 则不拷贝。默认是EnableWithAutoHeaderText ,Header 如果选择了的话,就拷贝。

1)编程方式实现剪切板的拷贝

Clipboard.SetDataObject(DataGridView1.GetClipboardContent())

2) DataGridView 的数据粘贴

实现剪切板的拷贝比较容易,但是实现DataGridView 的直接粘贴就比较难了。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。

以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。

//当前单元格是否选择的判断

if (DataGridView1.CurrentCell == null)

return;

int insertRowIndex = DataGridView1.CurrentCell.RowIndex;

// 获取剪切板的内容,并按行分割

string pasteText = Clipboard.GetText();

if (string.IsNullOrEmpty(pasteText))

return;

pasteText = pasteText.Replace(" ", " ");

pasteText = pasteText.Replace(' ', ' ');

pasteText.TrimEnd(new char[] { ' ' });

string[] lines = pasteText.Split(' ');

bool isHeader = true;

foreach (string line in lines)

{

// 是否是列头

if (isHeader)

{

isHeader = false;

continue;

}

// 按Tab 分割数据

string[] vals = line.Split(' ');

// 判断列数是否统一

if (vals.Length - 1 != DataGridView1.ColumnCount)

throw new ApplicationException("粘贴的列数不正确。");

DataGridViewRow row = DataGridView1.Rows[insertRowIndex];

// 行头设定

row.HeaderCell.Value = vals[0];

// 单元格内容设定

for (int i = 0; i < row.Cells.Count; i++)

{

row.Cells[i].Value = vals[i + 1];

}

// DataGridView的行索引+1

insertRowIndex++;

}

DataGridView单元格的ToolTip的设置:

DataGridView.ShowCellToolTips = True 的情况下,单元格的ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格,ToolTip 可以显示必要的信息。

1)设定单元格的ToolTip内容

[C#]

// 设定单元格的ToolTip内容

DataGridView1[0, 0].ToolTipText = "该单元格的内容不能修改";

// 设定列头的单元格的ToolTip内容

DataGridView1.Columns[0].ToolTipText = "该列只能输入数字";

// 设定行头的单元格的ToolTip内容

DataGridView1.Rows[0].HeaderCell.ToolTipText = "该行单元格内容不能修改";

2)CellToolTipTextNeeded 事件

在批量的单元格的ToolTip 设定的时候,一个一个指定那么设定的效率比较低,这时候可以利用CellToolTipTextNeeded 事件。当单元格的ToolTipText 变化的时候也会引发该事件。但是,当DataGridView的DataSource被指定且VirualMode=True的时候,该事件不会被引发。

[C#]

// CellToolTipTextNeeded事件处理方法

private void DataGridView1_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)

{

e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString();

}

DataGridView的右键菜单(ContextMenuStrip):

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell 有ContextMenuStrip 属性。可以通过设定ContextMenuStrip 对象来控制DataGridView 的右键菜单的显示。DataGridViewColumn 的ContextMenuStrip 属性设定了除了列头以外的单元格的右键菜单。DataGridViewRow 的ContextMenuStrip 属性设定了除了行头以外的单元格的右键菜单。DataGridViewCell 的ContextMenuStrip 属性设定了指定单元格的右键菜单。

// DataGridView 的ContextMenuStrip 设定

DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;

// 列的ContextMenuStrip 设定

DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;

// 列头的ContextMenuStrip 设定

DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;

// 行的ContextMenuStrip 设定

DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;

// 单元格的ContextMenuStrip 设定

DataGridView1[0, 0].ContextMenuStrip = this.ContextMenuStrip4;

对于单元格上的右键菜单的设定,优先顺序是:Cell > Row > Column > DataGridView

? CellContextMenuStripNeeded、RowContextMenuStripNeeded事件

利用CellContextMenuStripNeeded事件可以设定单元格的右键菜单,尤其但需要右键菜单根据单元格值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在DataGridView使用了DataSource绑定而且是VirtualMode的时候,该事件将不被引发。

//CellContextMenuStripNeeded事件处理方法

private void DataGridView1_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)

{

DataGridView dgv = (DataGridView)sender;

if (e.RowIndex < 0)

{

//列头的ContextMenuStrip设定

e.ContextMenuStrip = this.ContextMenuStrip1;

}

else if (e.ColumnIndex < 0)

{

//行头的ContextMenuStrip设定

e.ContextMenuStrip = this.ContextMenuStrip2;

}

else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)

{

//如果单元格值是整数时

e.ContextMenuStrip = this.ContextMenuStrip3;

}

}

同样,可以通过RowContextMenuStripNeeded事件来设定行的右键菜单。

//RowContextMenuStripNeeded事件处理方法

private void DataGridView1_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)

{

DataGridView dgv = (DataGridView)sender;

//当"Column1"列是Bool型且为True时、设定其的ContextMenuStrip

object boolVal = dgv["Column1", e.RowIndex].Value;

Console.WriteLine(boolVal);

if (boolVal is bool && (bool)boolVal)

{

e.ContextMenuStrip = this.ContextMenuStrip1;

}

}

CellContextMenuStripNeeded事件处理方法的参数中、「e.ColumnIndex=-1」表示行头、

「e.RowIndex=-1」表示列头。RowContextMenuStripNeeded则不存在「e.RowIndex=-1」的情况。

DataGridView的单元格的边框、网格线样式的设定:

1) DataGridView 的边框线样式的设定

DataGridView 的边框线的样式是通过DataGridView.BorderStyle 属性来设定的。BorderStyle 属性设定值是一个

BorderStyle 枚举:FixedSingle(单线,默认)、Fixed3D、None。

2) 单元格的边框线样式的设定

单元格的边框线的样式是通过DataGridView.CellBorderStyle 属性来设定的。CellBorderStyle 属性设定值是

DataGridViewCellBorderStyle 枚举。(详细参见MSDN)

另外,通过DataGridView.ColumnHeadersBorderStyle 和RowHeadersBorderStyle 属性可以修改DataGridView 的头部的单元格边框线样式。属性设定值是DataGridViewHeaderBorderStyle 枚举。(详细参见MSDN)

3)单元格的边框颜色的设定

单元格的边框线的颜色可以通过DataGridView.GridColor 属性来设定的。默认是ControlDarkDark 。但是只有在CellBorderStyle 被设定为Single、SingleHorizontal、SingleVertical 的条件下才能改变其边框线的颜色。同样,ColumnHeadersBorderStyle 以及RowHeadersBorderStyle 只有在被设定为Single 时,才能改变颜色。

4)单元格的上下左右的边框线式样的单独设定

CellBorderStyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到DataGridView.AdvancedCellBorderStyle属性。如示例:

[https://www.sodocs.net/doc/8d2160488.html,]

' 单元格的上边和左边线设为二重线

' 单元格的下边和右边线设为单重线

DataGridView1.AdvancedCellBorderStyle.Top = _ DataGridViewAdvancedCellBorderStyle.InsetDouble

DataGridView1.AdvancedCellBorderStyle.Right = _ DataGridViewAdvancedCellBorderStyle.Inset

DataGridView1.AdvancedCellBorderStyle.Bottom = _ DataGridViewAdvancedCellBorderStyle.Inset

DataGridView1.AdvancedCellBorderStyle.Left = _ DataGridViewAdvancedCellBorderStyle.InsetDouble

同样,设定行头单元格的属性是:AdvancedRowHeadersBorderStyle,设定列头单元格属性是:

AdvancedColumnHeadersBorderStyle。

DataGridView单元格表示值的自定义:

通过CellFormatting事件,可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色)

下面的示例:将“Colmn1”列的值改为大写。

//CellFormatting 事件处理方法

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

{

DataGridView dgv = (DataGridView)sender;

// 如果单元格是“Column1”列的单元格

if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)

{

// 将单元格值改为大写

string str = e.Value.ToString();

e.Value = str.ToUpper();

// 应用该Format,Format完毕。

e.FormattingApplied = true;

}

}

CellFormatting事件的DataGridViewCellFormattingEventArgs对象的Value属性一开始保存着未被格式化的值。当Value属性被设定表示用的文本之后,把FormattingApplied属性做为True,告知DataGridView文本已经格式化完毕。如果不这样做的话,DataGridView会根据已经设定的Format,NullValue,DataSourceNullValue,FormatProvider属性会将Value属性会被重新格式化一遍。

DataGridView用户输入时,单元格输入值的设定:

通过DataGridView.CellParsing 事件可以设定用户输入的值。下面的示例:当输入英文文本内容的时候,立即被改变为大写。

//CellParsing 事件处理方法

private void DataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)

{

DataGridView dgv = (DataGridView)sender;

//单元格列为“Column1”时

if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&

e.DesiredType == typeof(string))

{

//将单元格值设为大写

e.Value = e.Value.ToString().ToUpper();

//解析完毕

e.ParsingApplied = true;

}

}

DataGridView新加行的默认值的设定:

需要指定新加行的默认值的时候,可以在DataGridView.DefaultValuesNeeded事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的ReadOnly属性等。

// DefaultValuesNeeded 事件处理方法

private void DataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)

{

// 设定单元格的默认值

e.Row.Cells["Column1"].Value = 0;

e.Row.Cells["Column2"].Value = "-";

}

DataGridView的中的查找、,添加、删除行:

/// 查找指定的字串单元格

bool bFound = false;

String strFound = toolStrip1_cbxFindString.Text;

int nRows = dataGridView1.Rows.Count - 1;

int nCols = dataGridView1.Columns.Count - 1;

for (int i = 0; i != nRows; i++)

{

for (int j = 0; j != nCols; j++)

{

if (strFound == dataGridView1.Rows[i].Cells[j].Value.ToString())

{

dataGridView1.CurrentCell = dataGridView1[j, i];

bFound = true;

break;

}

if (bFound)

{

break;

}

}

if (bFound)

{

break;

}

}

if (!bFound)

{

MessageBox.Show("没有找到字串:" + strFound);

}

///

/// 向DataGirdView中添加行,显示在第一行,并选中该行

///

/// DataGridView对向

/// 总列数

/// 要添加的每列的值

public void AddRow(DataGridView dv, int colcount,params string[] colvalues) {

DataGridViewRow dr = new DataGridViewRow();

dr.CreateCells(dv);

for (int i = 0; i < colcount; i++)

{

dr.Cells[i].Value = colvalues[i];

}

dv.Rows.Insert(0, dr);

dv.CurrentCell = dv.Rows[0].Cells[0];

}

///

/// 删除DV中的指定行

///

/// DataGridView对向

/// 要删除的指定行

public void ReMoveRow(DataGridView dv, int colindex)

{

dv.Rows.Remove(dv.Rows[colindex]);

dv.ClearSelection();

}

}

0、(最基本的技巧)、获取某列中的某行(某单元格)中的内容

this.currentposition = this.dataGridView1.BindingContext [this.dataGridView1.DataSource, this.dataGridView1.DataMember].Position;bookContent =

this.database.dataSet.Tables[0].Rows

[this.currentposition][21].ToString().Trim();MessageBox.Show(bookContent);

1、自定义列

//定义列宽this.dataGridView1.Columns[0].Width =

80;this.dataGridView1.Columns[1].Width = 80;this.dataGridView1.Columns[2].Width = 180;this.dataGridView1.Columns[3].Width = 120;this.dataGridView1.Columns[4].Width = 120;Customize Cells and Columns in the Windows Forms DataGridView Control by Extending TheirBehavior and AppearanceHost Controls in Windows Forms DataGridView Cells

继承DataGridViewTextBoxCell 类生成新的Cell类,然后再继承DataGridViewColumn 生成新的Column类,并指定CellTemplate为新的Cell类。新生成的Column便可以增加到DataGridView中去。

2、自动适应列宽

Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView ControlSamples:

DataGridView.AutoSizeColumns(DataGridViewAutoSizeColumnCriteria.HeaderAndDisplaye dRows);DataGridView.AutoSizeColumn(DataGridViewAutoSizeColumnCriteria.HeaderOnly, 2, false);DataGridView.AutoSizeRow(DataGridViewAutoSizeRowCriteria.Columns,2, false);DataGridView.AutoSizeRows(DataGridViewAutoSizeRowCriteria.HeaderAndColumns, 0, dataGridView1.Rows.Count, false);

3、可以绑定并显示对象

Bind Objects to Windows Forms DataGridView Controls

4、可以改变表格线条风格

Change the Border and Gridline Styles in the Windows Forms DataGridView ControlSamples:this.dataGridView1.GridColor =

Color.BlueViolet;this.dataGridView1.BorderStyle =

BorderStyle.Fixed3D;this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;this.dataGridView1.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;this.dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

5、动态改变列是否显示,和动态改变列的显示顺序

Change the Order of the Columns in the Windows Forms DataGridView ControlSamples:customersDataGridView.Columns["CustomerID"].Visible =

false;customersDataGridView.Columns["ContactName"].DisplayIndex =

0;customersDataGridView.Columns["ContactTitle"].DisplayIndex =

1;customersDataGridView.Columns["City"].DisplayIndex =

2;customersDataGridView.Columns["Country"].DisplayIndex =

3;customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;

6、可以在列中显示图像

Display Images in Cells of the Windows Forms DataGridView ControlSamples:Icon treeIcon = new Icon(this.GetType(), "tree.ico");DataGridViewImageColumn iconColumn = new DataGridViewImageColumn ();iconColumn.Image = treeIcon.ToBitmap();https://www.sodocs.net/doc/8d2160488.html, = "Tree";iconColumn.HeaderText = "Nice tree";dataGridView1.Columns.Insert(2, iconColumn);

7、格式化显示内容:

Format Data in the Windows Forms DataGridView

ControlSamples:this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format =

"d";this.dataGridView1.DefaultCellStyle.NullValue = "no

entry";this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewWrapMode.Wrap;this.dataGridView1.Columns["CustomerName"].DefaultCellS tyle.Alignment =DataGridViewContentAlignment.MiddleRight;

8、在拖动列的滚动条时可以将指定的列冻结

Freeze Columns in the Windows Forms DataGridView ControlSamples:将指定列及以前的列固定不动this.dataGridView1.Columns["AddToCartButton"].Frozen = true;

9、获取选择的单元格,行,列

Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView ControlSamples:

10、显示录入时出现的错误信息

Handle Errors that Occur During Data Entry in the Windows Forms DataGridView ControlSamples:private void dataGridView1_DataError(object

sender,DataGridViewDataErrorEventArgs e){// If the data source raises an exception when a cell value is// commited, display an error message.if (e.Exception != null &&e.Context == https://www.sodocs.net/doc/8d2160488.html,mit){MessageBox.Show("CustomerID value must be unique.");}}

11、大数据量显示采用Virtual Mode

Implement Virtual Mode in the Windows Forms DataGridView Control

12、设置指定的列只读

Make Columns in the Windows Forms DataGridView Control Read-OnlySamples:dataGridView1.Columns["CompanyName"].ReadOnly = true;

13、移去自动生成的列

Remove Autogenerated Columns from a Windows Forms DataGridView ControlSample:dataGridView1.AutoGenerateColumns = true;dataGridView1.DataSource = customerDataSet;dataGridView1.Columns.Remove ("Fax");或:

dataGridView1.Columns["CustomerID"].Visible = false;

14、自定义选择模式

Set the Selection Mode of the Windows Forms DataGridView ControlSample:

this.dataGridView1.SelectionMode =

DataGridViewSelectionMode.FullRowSelect;this.dataGridView1.MultiSelect = false;

15、自定义设定光标进入单元格是否编辑模式(编辑模式)

Specify the Edit Mode for the Windows Forms DataGridView

Controlthis.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

16、新行指定默认值

Specify Default Values for New Rows in the Windows Forms DataGridView ControlSample:private void dataGridView1_DefaultValuesNeeded(object sender,

System.Windows.Forms.DataGridViewRowEventArgs e){e.Row.Cells["Region"].Value = "WA";e.Row.Cells["City"].Value = "Redmond";e.Row.Cells["PostalCode"].Value =

"98052-6399";e.Row.Cells["Region"].Value = "NA";e.Row.Cells["Country"].Value = "USA";e.Row.Cells["CustomerID"].Value = NewCustomerId();}

17、数据验证

Validate Data in the Windows Forms DataGridView ControlSamples:private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e){// Validate the CompanyName entry by disallowing empty strings.if

(dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName"){if

(e.FormattedValue.ToString() ==

String.Empty){dataGridView1.Rows[e.RowIndex].ErrorText ="Company Name must not be empty";e.Cancel = true;}}}

18、数据提交到dataset中

DataSet ds = new DataSet("MyDataSet");ds.Tables[biaom.Trim()].Rows.Clear();try{for (int i = 0; i < dataGridView1.Rows.Count - 1; i++){DataTable dt =

ds.Tables[biaom.Trim()];DataRow myrow = ds.Tables[biaom.Trim()].NewRow();for (int j = 0; j < dataGridView1.Columns.Count; j++){myrow[j] =

Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);}ds.Tables[biaom.Trim()].Rows.Add (myrow);}}catch (Exception){MessageBox.Show("输入类型错误!");return;}

微软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);

DataGridView的用法

在C# WinForm下做过项目的朋友都知道,其中的DataGridView控件默认只支持DataGridViewButtonColumn、DataGridViewCheckBoxColumn、DataGridViewComboBoxColumn、DataGridViewImageColumn、DataGridViewLinkColumn和DataGridViewTextBoxColumn六种列类型,如果你想要在DataGridView的列中添加其它的子控件,则需要自己实现DataGridViewColumn和DataGridViewCell,这就意味着你需要从现有的列中继承并改写一些方法,如实现一个支持单选按钮的列,或支持三种选择状态的多选按钮的列。 上面两个截图分别为RadioButton列和支持三种状态的CheckBox列在DataGridView中的实现效果,我是在Windows 2003中实现的,因此显示的效果跟在XP和Vista下有些区别,Vista下CheckBox的第三种状态(不确定状态)显示出来的效果是一个实心的蓝色方块。 下面我看具体来看看如何实现这两种效果。 要实现自定义的DataGridView列,你需要继承并改写两个类,一个是基于DataGridViewColumn的,一个是基于DataGridViewCell的,因为

RadionButton和CheckBox的实现原理类似,因此我们可以将这两种列采用同一种方法实现。创建DataGridViewDisableCheckBoxCell和DataGridViewDisableCheckBoxColumn两个类,分别继承自DataGridViewCheckBoxCell和DataGridViewCheckBoxColumn。代码如下: public class DataGridViewDisableCheckBoxCell: DataGridViewCheckBoxCell { public bool Enabled { get; set; } // Override the Clone method so that the Enabled property is copied. public override object Clone() { DataGridViewDisableCheckBoxCell cell = (DataGridViewDisableCheckBoxCell)base.Clone(); cell.Enabled = this.Enabled; return cell; } // By default, enable the CheckBox cell. public DataGridViewDisableCheckBoxCell() { this.Enabled = true; } // Three state checkbox column cell protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { // The checkBox cell is disabled, so paint the border, background, and disabled checkBox for the cell. if (!this.Enabled) { // Draw the cell background, if specified. if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background) { SolidBrush cellBackground = new SolidBrush(cellStyle.BackColor); graphics.FillRectangle(cellBackground,

DataGridView控件用法合集

DataGridView控件用法合集 目录 DataGridView控件用法合集(一) 1. DataGridView当前的单元格属性取得、变更 2. DataGridView编辑属性 3. DataGridView最下面一列新追加行非表示 4. DataGridView判断当前选中行是否为新追加的行 5. DataGridView删除行可否设定 6. DataGridView行列不表示和删除 DataGridView控件用法合集(二) 7. DataGridView行列宽度高度设置为不能编辑 8. DataGridView行高列幅自动调整 9. DataGridView指定行列冻结 10. DataGridView列顺序变更可否设定 11. DataGridView行复数选择 12. DataGridView选择的行、列、单元格取得 DataGridView控件用法合集(三) 13. DataGridView指定单元格是否表示 14. DataGridView表头部单元格取得 15. DataGridView表头部单元格文字列设定 16. DataGridView选择的部分拷贝至剪贴板 17.DataGridView粘贴 18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息) DataGridView控件用法合集(四) 19. DataGridView中的ContextMenuStrip属性 20. DataGridView指定滚动框位置 21. DataGridView手动追加列 22. DataGridView全体分界线样式设置 23. DataGridView根据单元格属性更改显示内容 24. DataGridView新追加行的行高样式设置る 25. DataGridView新追加行单元格默认值设置 DataGridView中输入错误数据的处理(五) 26. DataGridView单元格数据错误标签表示 27. DataGridView单元格内输入值正确性判断 28. DataGridView单元格输入错误值事件的捕获 DataGridView控件用法合集(六) 29. DataGridView行排序(点击列表头自动排序的设置) 30. DataGridView自动行排序(新追加值也会自动排序) 31. DataGridView自动行排序禁止情况下的排序 32. DataGridView指定列指定排序 DataGridView控件用法合集(七) 33. DataGridView单元格样式设置 34. DataGridView文字表示位置的设定 35. DataGridView单元格内文字列换行 36. DataGridView单元格DBNull值表示的设定 37. DataGridView单元格样式格式化 38. DataGridView指定单元格颜色设定

datagridview在vbnet中的操作技巧.

DataGridView在https://www.sodocs.net/doc/8d2160488.html,中的操作技巧目录: 1、取得或者修改当前单元格的内容 2、设定单元格只读 3、不显示最下面的新行 4、判断新增行 5、行的用户删除操作的自定义 6、行、列的隐藏和删除 7、禁止列或者行的Resize 8、列宽和行高以及列头的高度和行头的宽度的自动调整 9、冻结列或行 10、列顺序的调整 11、行头列头的单元格 12、剪切板的操作 13、单元格的ToolTip的设置 14、右键菜单(ContextMenuStrip的设置 15、单元格的边框、网格线样式的设定 16、单元格表示值的设定 17、用户输入时,单元格输入值的设定 18、设定新加行的默认值

1、DataGridView 取得或者修改当前单元格的内容: 当前单元格指的是DataGridView 焦点所在的单元格,它可以通过DataGridView 对象的CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null [https://www.sodocs.net/doc/8d2160488.html,] ' 取得当前单元格内容MessageBox.Show(DataGridView1.CurrentCell.Value ' 取得当前单元格的列Index MessageBox.Show(DataGridView1.CurrentCell.ColumnIndex ' 取得当前单元格的行Index MessageBox.Show(DataGridView1.CurrentCell.RowIndex 另外,使用DataGridView.CurrentCellAddress 属性(而不是直接访问单元格来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 和 列:DataGridView.CurrentCellAddress.X 。这对于避免取消共享行的共享非常有用。 当前的单元格可以通过设定DataGridView 对象的CurrentCell 来改变。可以通过CurrentCell 来设定 DataGridView 的激活单元格。将CurrentCell 设为Nothing(null 可以取消激活的单元格。[https://www.sodocs.net/doc/8d2160488.html,] ' 设定(0, 0 为当前单元格 DataGridView1.CurrentCell = DataGridView1(0, 0 -------------------------------------------------------------------------------- 2、DataGridView 设定单元格只读:

vb6.0中DataGrid控件的使用

vb6.0中DataGrid控件的使用 https://www.sodocs.net/doc/8d2160488.html,/ivu890103@126/blog/static/117734463201122782022384/ DataGrid 控件是一种类似于电子数据表的绑定控件,可以显示一系列行和列来表示 Recordset 对象的记录和字段。可以使用 DataGrid 来创建一个允许最终用户阅读和写入到绝大多数数据库的应用程序。DataGrid 控件可以在设计时快速进行配置,只需少量代码或无需代码。当在设计时设置了DataGrid 控件的 DataSource 属性后,就会用数据源的记录集来自动填充该控件,以及自动设置该控件的列标头。然后您就可以编辑该网格的列;删除、重新安排、添加列标头、或者调整任意一列的宽度。 在运行时,可以在程序中切换 DataSource 来察看不同的表,或者可以修改当前数据库的查询,以返回一个不同的记录集合。 注意 DataGrid 控件与 Visual Basic 5.0中的 DBGrid 是代码兼容的,除了一个例外:DataGrid 控件不支持 DBGrid 的“解除绑定模式”概念。DBGrid 控件包括在 Visual Basic 的 Tools 目录中。 可能的用法 查看和编辑在远程或本地数据库中的数据。 与另一个数据绑定的控件(诸如 DataList 控件)联合使用,使用 DataGrid控件来显示一个表的记录,这个表通过一个公共字段链接到由第二个数据绑定控件所显示的表。 使用 DataGrid 控件的设计时特性 可以不编写任何代码,只通过使用 DataGrid 控件的设计时特性来创建一个数据库应用程序。下面的说明概要地说明了在实现 DataGrid 控件的典型应用时的一般步骤。完整的循序渐进的指示,请参阅主题“DataGrid方案1: 使用 DataGrid 控件创建一个简单数据库应用程序”。 要在设计时实现一个 DataGrid 控件 1. 为要访问的数据库创建一个 Microsoft 数据链接 (.MDL) 文件。请参阅“创建 Northwind OLE DB 数据链接”主题,以获得一个示例。 2. 在窗体上放置一个 ADO Data 控件,并将其 ConnectionString 属性设置为在第 1 步中所创建的OLE DB 数据源。 3. 在这个 Ado Data 控件的 RecordSource 属性中输入一条将返回一个记 录集的 SQL 语句。例如,Select * From MyTableName Where CustID = 12 4. 在窗体上放置一个 DataGrid 控件,并将其 DataSource 属性设置为这个 ADO Data 控件。 5. 右键单击该 DataGrid 控件,然后单击“检索字段”。 6. 右键单击该 DataGrid 控件,然后单击“编辑”。 7. 重新设置该网格的大小、删除或添加网格的列。 8. 右键单击该 DataGrid 控件,然后单击“属性”。 9. 使用“属性页”对话框来设置该控件的适当的属性,将该网格配置为所需的外观和行为。 在运行时更改显示的数据

VB6.0中DataGrid的应用

使用DataGrid 控件 DataGrid 控件是一种类似于电子数据表的绑定控件,可以显示一系列行和列来表示Recordset 对象的记录和字段。可以使用DataGrid 来创建一个允许最终用户阅读和写入到绝大多数数据库的应用程序。DataGrid 控件可以在设计时快速进行配置,只需少量代码或无需代码。当在设计时设置了DataGrid 控件的DataSource 属性后,就会用数据源的记录集来自动填充该控件,以及自动设置该控件的列标头。然后您就可以编辑该网格的列;删除、重新安排、添加列标头、或者调整任意一列的宽度。 在运行时,可以在程序中切换DataSource 来察看不同的表,或者可以修改当前数据库的查询,以返回一个不同的记录集合。 注意DataGrid 控件与Visual Basic 5.0中的DBGrid 是代码兼容的,除了一个例外:DataGrid 控件不支持DBGrid 的“解除绑定模式”概念。DBGrid 控件包括在Visual Basic 的Tools 目录中。 可能的用法 查看和编辑在远程或本地数据库中的数据。 与另一个数据绑定的控件(诸如DataList 控件)联合使用,使用DataGrid控件来显示一个表的记录,这个表通过一个公共字段链接到由第二个数据绑定控件所显示的表。 使用DataGrid 控件的设计时特性 可以不编写任何代码,只通过使用DataGrid 控件的设计时特性来创建一个数据库应用程序。下面的说明概要地说明了在实现DataGrid 控件的典型应用时的一般步骤。完整的循序渐进的指示,请参阅主题“DataGrid 方案1: 使用DataGrid 控件创建一个简单数据库应用程序”。要在设计时实现一个DataGrid 控件 1. 为要访问的数据库创建一个Microsoft 数据链接(.MDL) 文件。请参阅“创建Northwind OLE DB 数据链接”主题,以获得一个示例。 2. 在窗体上放置一个ADO Data 控件,并将其ConnectionString 属性设置为在第1 步中所创建的OLE DB 数据源。 3. 在这个Ado Data 控件的RecordSource 属性中输入一条将返回一个记 录集的SQL 语句。例如,Select * From MyTableName Where CustID = 12 4. 在窗体上放置一个DataGrid 控件,并将其DataSource 属性设置为这个ADO Data 控件。 5. 右键单击该DataGrid 控件,然后单击“检索字段”。 6. 右键单击该DataGrid 控件,然后单击“编辑”。 7. 重新设置该网格的大小、删除或添加网格的列。 8. 右键单击该DataGrid 控件,然后单击“属性”。 9. 使用“属性页”对话框来设置该控件的适当的属性,将该网格配置为所需的外观和行为。在运行时更改显示的数据 在创建了一个使用设计时特性的网格后,也可以在运行时动态地更改该网格的数据源。下面介绍实现这一功能的通常方法。 更改DataSource 的RecordSource 更改所显示的数据的最通常方法是改变该DataSource 的查询。例如,如果DataGrid 控件使用一个ADO Data控件作为其DataSource,则重写RecordSource和刷新该ADO Data 控件都将改变所显示的数据。 ' ADO Data 控件连接的是Northwind 数据库的' Products 表。新查询查找所有 ' SupplierID = 12 的记录。

DataGridView实现数据的快速输入

C#利用DataGridView实现数据的快速输入 网络编程2008-03-11 16:04:03 阅读313 评论0 字号:大中小订阅 在做管理软件时,常常需要表格输入功能。表格输入极大地加快了数据输入,提高了工作效率,当然也提高了软件的竞争性。笔者最近用C#在做一套CRM时,成功地使用C# 2005里面的表格控件DataGridView 实现了表格输入功能,现在就把具体实现与各位分享: 1. 初始化工作 (1) 在Vs 2005 里面新建一个C# WinForm 应用程序:DataGridViewTest (2) 在窗体Form1上拖一个DataGridView控件:DataGridView1 (3) 在DataGridView1里添加两个列: Column1: 类型:DataGridViewComboBoxColumn HeaderText:时间 DataPropertyName:DutyTime Column2: 类型:DataGridViewTextBoxColumn HeaderText:时间 DataPropertyName:DutyTime (4)在Form1类中添加两个私有属性: private DataTable m_Table;//输入组合框控件的下拉数据 private DataTable m_DataTable;//与表格绑定的DataTable,即用户输入的最终数据 (5)在Form1类里面定义一个结构体 public struct MyRowData { public MyRowData(int no, string enDay, string cnDay) { No = no; EnDay = enDay; CnDay = cnDay; } public int No; public string EnDay; public string CnDay; } (6) 在Form1的load事件Form1_Load(object sender, EventArgs e) 加上以下初始化代码: this.dataGridView1.AllowUserToAddRows = true; this.dataGridView1.AllowUserToDeleteRows = true; this.dataGridView1.AutoGenerateColumns = false;

C#中DatagridView单元格动态绑定控件

C#中DatagridView单元格动态绑定控件 C#中DatagridView单元格动态绑定控件 我们在使用DatagridView的列样式的时候很方便,可以设置成comboboxcolumn,textboxcolumn等等样式,使用起来非常方便,但是,这样设置的列都采用同一种样式.对同一列采用多种样式的,就需要单独对单元格进行操作了. 具体方法如下: 1.实例化一个定义好的控件:如combobox 2.初始化combobox 控件3.获取private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.CurrentCell.ReadOnly == false && dataGridView1.CurrentCell.RowIndex == 2) // combobox显示条件 { comboBox1.Text = dataGridView1.CurrentCell.Value.ToString(); //对combobox 赋值R = dataGridView1.GetCellDisplayRectangle(dataGridView1.Curre ntCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false); //获取单元格位置

comboBox1.SetBounds(R.X + dataGridView1.Location.X, R.Y + dataGridView1.Location.Y, R.Width, R.Height); //重新定位combobox.中间有坐标位置的转换 comboBox1.Visible = true; } else comboBox1.Visible = false; } 4.将combobox的值写回到单元格 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { dataGridView1.CurrentCell.Value = comboBox1.Text; }

C#用DataGridview 做的表格效果

C#用DataGridview 做的表格效果 private void Form1_Load(object sender, EventArgs e) { DataGridViewComboBoxColumn boxc = new DataGridViewComboBoxColumn();//创建下拉框 boxc.HeaderText = "国家";//设定标题头 boxc.Items.Add("China");//设定下拉框内容 boxc.Items.Add("England"); boxc.Items.Add("U.S.A"); boxc.Items.Add("Japan"); this.dataGridView1.Columns.Add(boxc);//将下拉框添加到datagridview中 DataGridViewTextBoxColumn textc = new DataGridViewTextBoxColumn();//创建文本框字段 textc.HeaderText = "公司"; this.dataGridView1.Columns.Add(textc); textc = new DataGridViewTextBoxColumn(); textc.HeaderText = "描述"; this.dataGridView1.Columns.Add(textc); DataGridViewButtonColumn butc = new DataGridViewButtonColumn();//创建按钮字段 butc.HeaderText = "设置"; butc.Text = "设置"; butc.DefaultCellStyle.ForeColor = Color.Black; butc.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.ButtonFace); butc.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; butc.Width = 150; https://www.sodocs.net/doc/8d2160488.html,eColumnTextForButtonValue = true;//如果为false,则不显示button上的text this.dataGridView1.Columns.Add(butc); butc = new DataGridViewButtonColumn(); butc.HeaderText = "删除"; butc.Text = "删除"; butc.DefaultCellStyle.ForeColor = Color.Black; butc.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.ButtonFace); butc.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; butc.Width = 150;

简单的DataGrid控件在WPF中绑定List集合数据

简单的DataGrid控件在中绑定List集合数据 1.在界面中添加DataGrid控件,用来显示系统的操作记录,界面和程序如下: 注释:AutoGenerateColumns这个属性为true时,控件的数据源list会按照自己的格式自动显示在控件上;如果这个属性为false,list的数据不会自动显示在datagrid上。 2.后台逻辑 List list = new List(); DateFilter filter = new DateFilter(Year,Month,Day); list = AllMananger.GetList(filter); //以上是我通过我的办法得到的list,要把此list绑定到DataGrid上。 this.operationGrid.ItemsSource = list; 现在把需要的list绑定到控件的ItemSource属性上。 3.Blinding 因为我的OperationRecord类中有三个属性,分别是OperationTime、OperationContent、OperationUser。 此时,把List list分别绑定到datagrid中的三个列中,按照我们对应的列名。例如:Binding="{Binding OperationTime }"

datagridview绑定数据源的几种常见方式

datagridview绑定数据源的几种常见方式datagridview绑定数据源的几种常见方式 //////////////开始以前,先认识一下WinForm控件数据绑定的两种形式,简单数据绑定和复杂数据绑定。 //////////////1)简单数据绑定 //////////////////using (SqlConnection conn = new SqlConnection(Config urationManager.ConnectionStrings["connStr"].ToString())) //////////////////{ ////////////////// SqlDataAdapter sda = new SqlDataAdapter("Select * Fr om T_Class Where F_Type='Product' order by F_RootID,F_Orders", conn); ////////////////// DataSet Ds = new DataSet(); ////////////////// sda.Fill(Ds, "T_Class"); ////////////////// //使用DataSet绑定时,必须同时指明DateMember ////////////////// //this.dataGridView1.DataSource = Ds; ////////////////// //this.dataGridView1.DataMember = "T_Class"; ////////////////// //也可以直接用DataTable来绑定 ////////////////// this.dataGridView1.DataSource = Ds.Tables["T_Class"]; //////////////////}

DATAGRID的用法

前几天打算尝试下DataGrid的用法,起初以为应该很简单,可后来被各种使用方法和功能实现所折磨。网络上的解决方法太多,但也太杂。没法子,我只好硬着头皮阅览各种文献资料,然后不断的去尝试,总算小有成果。因此,把我学到的和大家分享一下,相信这篇文章会让你再很短的时间内学会DataGrid的大部分主要功能,而且很多难点都可以在里面找到解决方案。 由于涉及的应用比较多,所以篇幅会很长。但可以确保各个版块相互独立,总共4个部分 1.数据绑定 2.DataGrid的增改删功能 3.DataGrid的分页实现 4.DataGrid的样式设计 先上一张截图,让你大概知道自己需要的功能是否在这张图里有所实现。 PS:使用技术:WPF+https://www.sodocs.net/doc/8d2160488.html, Entity Framework

1.数据绑定(涉及DataGrid绑定和Combox绑定) 在DataGrid中同时包含“自动生成列”与“用户自定义列”由属性AutoGenerateColumns控制。 默认情况下,DataGrid将根据数据源自动生成列。下图列出了生成的列类型。 如果AutoGenerateColumns="True",我们只需要如下几行代码 后台dataGrid1.ItemsSource=infoList;//infoList为内容集合(这是我从数据库中获取的记录集合类型为List) PS:因为这里给dataGrid1绑定了数据源,所以下面绑定的字段都是infoList中的字段名称,同样也对应着我数据表中的字段名。里面包含FID,公司名称,职员姓名,性别,年龄,职务。解释下,怕大家无法理解Binding后面的值是如何来的了 显然这种数据绑定非常的容易,如果对表格要求不高,这中无疑是最简单方便的。

DataGridView中数据存入数据库方法

DataGridView做了新的数据显示控件加入到了.Net 05中,其强大的编辑能力让其成为了数据显示中必不可少的控件。目前对于DataGridView中的更新讲的挺多的,但直接的插入数据好像讲的不是太多,下面就以我的例子说明一下。 1、首先新建一个项目。 2、建立一个数据库连接类LinkDataBase。因为数据库操作有很多都是重复性工作,所以我们写一个类来简化对数据库的操作。 using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Sql; namespace Test ...{ class LinkDataBase ...{ //设置连接字符串 private string strSQL; //与数据库连接 private string connectionString = "Data Source=Localhost;Initial Catalog=Test;Integr ated Security=True"; private SqlConnection myConnection; private SqlCommandBuilder sqlCmdBld; private DataSet ds = new DataSet(); private SqlDataAdapter da; public LinkDataBase() ...{ } //根据输入的SQL语句检索数据库数据 public DataSet SelectDataBase(string tempStrSQL, string tempTableName) ...{ this.strSQL = tempStrSQL; this.myConnection = new SqlConnection(connectionString); this.da = new SqlDataAdapter(this.strSQL, this.myConnection); this.ds.Clear(); this.da.Fill(ds, tempStrSQL); //返回填充了数据的DataSet,其中数据表以tempTableName给出的字符串命名 return ds; } //数据库数据更新(传DataSet和DataTable的对象) public DataSet UpdateDataBase(DataSet changedDataSet, string tableName) ...{ this.myConnection = new SqlConnection(connectionString);

NET新手指南:轻松自定义DataGridView控件

.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、如果连接工作正常,点击确定返回向导窗口,然后点击下一步继续;

DataGridView自定义列

Winform下DataGridView控件自定义列System.Windows.Forms.DataGridView控件是net下,数据显示使用最多的控件之一,但是Datagridviewk控件列类型却仅仅只有6中 分别是button 、checkbox、combobox、image、link、textbox 等6种常见类型。这很难满足我们日常开发需要。如果需要复杂的应用,要么找第三方控件,要么只能自己开发。而功能强大的第三方控件往往是需要付费的。但我们开发需要的很可能只是简单的功能,如果为了某个简单功能而专门购买一个控件对于个人来说有些得不偿失。 那么我们只剩下自己开发一途。幸运的是DataGridView控件容许我们进行二次开发,可以自定义我们需要的控件列。下图就是自定义日期输入自定义列,通过下面的例子,你完全可以开发出自己需要的功能列。下面给出https://www.sodocs.net/doc/8d2160488.html,和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"; }

C#中DataGridView的使用

C#中DataGridView的使用 1.首先,连接数据库 Copy code public void Connect()  在C#中,使用DataGridView控件能很方便的显示从数据库中检索的数据. 1.首先,连接数据库 Copy code public void Connect() { string strConn = string.Format("Data Source = IP;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DataBaseName;User ID = UserID;"); using (sqlConnection cnn = new SqlConnection(strConn)) { try { cnn.Open(); bConn = true; } catch (Exception exp) { MessageBox.Show(exp.Message); bConn = false; } } } 2.构造SQL语句去数据库查询,并奖结果放到DataGridView控件 Copy code string strSql = string.Format("select * from TableName where ID < 50 order by ID"); DataSet dataset = new DataSet(); SqlDataAdapter myDataAdapter = new SqlDataAdapter(strSql, cnn); myDataAdapter.Fill(dataset); //这句跟下面的顺序不能颠倒 dataGridView1.DataSource = dataset.Tables[0];//填充 3.添加DataGridView控件的右键菜单 Copy code //在CellMouseClick里操作 private void DataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (e.RowIndex >= 0)

相关主题