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指定单元格颜色设定
40. DataGridView根据单元格值设定单元格样式
DataGridView控件用法合集(八)
41. DataGridView设置单元格背景颜色
42. DataGridView行样式描画
43. DataGridView显示行号
44. DataGridView焦点所在单元格焦点框不显示的设定DataGridView控件用法合集(九)
45. DataGridView中显示选择框CheckBox
46. DataGridView中显示下拉框ComboBox
47. DataGridView单击打开下拉框
48. DataGridView中显示按钮
49. DataGridView中显示链接
50. DataGridView中显示图像
DataGridView控件用法合集(十)
51. DataGridView编辑中单元格控件取得
52. DataGridView输入自动完成
53. DataGridView单元格编辑时键盘KEY事件取得
54. DataGridView下拉框(ComboBox)单元格编辑时事件取得
55. DataGridView下拉框(ComboBox)单元格允许文字输入设定DataGridView控件用法合集(十一)
56. DataGridView根据值不同在另一列中显示相应图片
57. DataGridView中显示进度条(ProgressBar)
58. DataGridView中添加MaskedTextBox
DataGridView控件用法合集(十二)
59. DataGridView中Enter键按下焦点移至旁边的单元格
60. DataGridView行集合化(Group)
正文
DataGridView控件用法合集(一)
1. DataGridView当前的单元格属性取得、变更
2. DataGridView编辑属性
3. DataGridView最下面一列新追加行非表示
4. DataGridView判断当前选中行是否为新追加的行
5. DataGridView删除行可否设定
6. DataGridView行列不表示和删除
1.当前的单元格属性取得、变更
[https://www.wendangku.net/doc/257335622.html,]
'当前选中单元的值
Console.WriteLine(DataGridView1.CurrentCell.Value)
'当前列的Index值
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex)
'当前单元的行Index值
Console.WriteLine(DataGridView1.CurrentCell.RowIndex)
'将控件中(0, 0)处的值,赋给当前单元格.
DataGridView1.CurrentCell = DataGridView1(0, 0)
2.DataGridView编辑属性
全部单元格编辑属性
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.ReadOnly = True
指定行列单元格编辑属性
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.Columns(1).ReadOnly = True
DataGridView1.Rows(2).ReadOnly = True
DataGridView1(0, 0).ReadOnly = True
根据条件判断单元格的编辑属性
下例中column2的值是True的时候,Column1设为可编辑
[https://www.wendangku.net/doc/257335622.html,]
Private Sub DataGridView1_CellBeginEdit(ByVal sender As Object, _
ByVal e As DataGridViewCellCancelEventArgs) _
Handles DataGridView1.CellBeginEdit
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
Not CBool(dgv("Column2", e.RowIndex).Value) Then
e.Cancel = True
End If
End Sub
3.DataGridView最下面一列新追加行非表示
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.AllowUserToAddRows = False
4.判断当前选中行是否为新追加的行
[https://www.wendangku.net/doc/257335622.html,]
If DataGridView1.CurrentRow.IsNewRow Then
Console.WriteLine("現在のセルがある行は、新しい行です。")
Else
Console.WriteLine("現在のセルがある行は、新しい行ではありません。") End If
5. DataGridView删除行可否设定
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.AllowUserToDeleteRows = False
根据条件判断当前行是否要删除
[https://www.wendangku.net/doc/257335622.html,]
Private Sub DataGridView1_UserDeletingRow(ByVal sender As Object, _
ByVal e As DataGridViewRowCancelEventArgs) _
Handles https://www.wendangku.net/doc/257335622.html,erDeletingRow
If MessageBox.Show("この列を削除しますか?", "削除の確認", _
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> _
Windows.Forms.DialogResult.OK Then
End If
End Sub
6. DataGridView行列不表示和删除
行列不表示
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1のはじめの列を非表示にする
DataGridView1.Columns(0).Visible = False
'DataGridView1のはじめの行を非表示にする
DataGridView1.Rows(0).Visible = False
行列表头部分不表示
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.ColumnHeadersVisible = False
DataGridView1.RowHeadersVisible = False
指定行列删除
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.Columns.Remove("Column1")
DataGridView1.Columns.RemoveAt(0)
DataGridView1.Rows.RemoveAt(0)
选择的行列删除(多行列)
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1で選択されているすべての行を削除する
Dim r As DataGridViewRow
For Each r In DataGridView1.SelectedRows
If Not r.IsNewRow Then
DataGridView1.Rows.Remove(r)
End If
Next r
DataGridView控件用法合集(二)
7. DataGridView行列宽度高度设置为不能编辑
8. DataGridView行高列幅自动调整
9. DataGridView指定行列冻结
10. DataGridView列顺序变更可否设定
11. DataGridView行复数选择
12. DataGridView选择的行、列、单元格取得
7. DataGridView行列宽度高度设置为不能编辑
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1の列の幅をユーザーが変更できないようにするDataGridView1.AllowUserToResizeColumns = False
'DataGridView1の行の高さをユーザーが変更できないようにするDataGridView1.AllowUserToResizeRows = False
指定行列宽度高度设置为不能编辑
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1のはじめの列の幅をユーザーが変更できないようにする
'DataGridView1のはじめの行の高さをユーザーが変更できないようにするDataGridView1.Rows(0).Resizable = DataGridViewTriState.False
列幅行高最小值设定
[https://www.wendangku.net/doc/257335622.html,]
'一番はじめの列の幅の最小を100ピクセルとする
DataGridView1.Columns(0).MinimumWidth = 100
'一番はじめの行の高さの最小を50ピクセルとする
DataGridView1.Rows(0).MinimumHeight = 50
行列表头部分行高列幅设置为不能编辑
[https://www.wendangku.net/doc/257335622.html,]
'列ヘッダーの高さを変更できないようにする
DataGridView1.ColumnHeadersHeightSizeMode = _
DataGridViewColumnHeadersHeightSizeMode.DisableResizing
'行ヘッダーの幅を変更できるようにする
DataGridView1.RowHeadersWidthSizeMode = _
DataGridViewRowHeadersWidthSizeMode.EnableResizing
8. DataGridView行高列幅自动调整
[https://www.wendangku.net/doc/257335622.html,]
'ヘッダーとすべてのセルの内容に合わせて、列の幅を自動調整するDataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells 'ヘッダーとすべてのセルの内容に合わせて、行の高さを自動調整するDataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
表头部分行高列幅自动调整
[https://www.wendangku.net/doc/257335622.html,]
'列ヘッダーの高さが自動調整されるようにする
DataGridView1.ColumnHeadersHeightSizeMode = _
DataGridViewColumnHeadersHeightSizeMode.AutoSize
'行ヘッダーの幅が自動調整されるようにする
DataGridView1.RowHeadersWidthSizeMode = _
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
指定列自动调整
[https://www.wendangku.net/doc/257335622.html,]
'はじめの列の幅を自動調整する
DataGridView1.Columns(0).AutoSizeMode = _
DataGridViewAutoSizeColumnMode.DisplayedCells
9. DataGridView指定行列冻结
列冻结(当前列以及左侧做所有列)
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1の左側2列を固定する
DataGridView1.Columns(1).Frozen = True
行冻结(当前行以及上部所有行)
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1の上部2行を固定する
DataGridView1.Rows(2).Frozen = True
指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1(0, 0). Frozen = True
10. DataGridView列顺序变更可否设定
[https://www.wendangku.net/doc/257335622.html,]
DataGridView1.AllowUserToOrderColumns = True
但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
变更后列位置取得
[https://www.wendangku.net/doc/257335622.html,]
'列"Column1"の現在の位置を取得する
Console.WriteLine(DataGridView1.Columns("Column1").DisplayIndex)
'列"Column1"を先頭に移動する
DataGridView1.Columns("Column1").DisplayIndex = 0
11. DataGridView行复数选择
复数行选择不可
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1でセル、行、列が複数選択されないようにする
DataGridView1.MultiSelect = False
单元格选择的时候默认为选择整行
[https://www.wendangku.net/doc/257335622.html,]
'セルを選択すると行全体が選択されるようにする
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
12. DataGridView选择的行、列、单元格取得
[https://www.wendangku.net/doc/257335622.html,]
'選択されているセルを表示
Console.WriteLine("選択されているセル")
For Each c As DataGridViewCell In DataGridView1.SelectedCells
Console.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex)
Next c
'選択されている行を表示
Console.WriteLine("選択されている行")
For Each r As DataGridViewRow In DataGridView1.SelectedRows
Console.WriteLine(r.Index)
Next r
'選択されている列を表示
Console.WriteLine("選択されている列")
For Each c As DataGridViewColumn In DataGridView1.SelectedColumns
Console.WriteLine(c.Index)
Next c
指定行、列、单元格取得
[https://www.wendangku.net/doc/257335622.html,]
'(0, 0)のセルを選択する
DataGridView1(0, 0).Selected = True
'インデックス1の行を選択する
DataGridView1.Rows(1).Selected = True
'インデックス2の列を選択する
DataGridView1.Columns(2).Selected = True
DataGridView控件用法合集(三)
13. DataGridView指定单元格是否表示
14. DataGridView表头部单元格取得
15. DataGridView表头部单元格文字列设定
16. DataGridView选择的部分拷贝至剪贴板
17.DataGridView粘贴
18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息)
13. DataGridView指定单元格是否表示
[https://www.wendangku.net/doc/257335622.html,]
If Not DataGridView1(0, 0).Displayed AndAlso _
DataGridView1(0, 0).Visible Then
DataGridView1.CurrentCell = DataGridView1(0, 0)
End If
14. DataGridView表头部单元格取得
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1のはじめの列のテキストを変更する
DataGridView1.Columns(0).HeaderCell.Value = "はじめの列"
'DataGridView1のはじめの行のテキストを変更する
DataGridView1.Rows(0).HeaderCell.Value = "はじめの行"
'DataGridView1の左上隅のセルのテキストを変更するDataGridView1.TopLeftHeaderCell.Value = "左上"
15. DataGridView表头部单元格文字列设定
更改列Header表示文字列
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1のはじめの列のテキストを変更する
DataGridView1.Columns(0).HeaderText = "はじめの列"
更改行Header表示文字列
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1の行ヘッダーに行番号を表示する
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).HeaderCell.Value = i.ToString()
Next i
'行ヘッダーの幅を自動調節する
DataGridView1.AutoResizeRowHeadersWidth( _
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders) 最左上Header单元格文字列
[https://www.wendangku.net/doc/257335622.html,]
'左上隅のヘッダーセルに"/"と表示する
DataGridView1.TopLeftHeaderCell.Value = "/"
16. DataGridView选择的部分拷贝至剪贴板
拷贝模式设定
[https://www.wendangku.net/doc/257335622.html,]
'ヘッダーをコピーしないようにする
DataGridView1.ClipboardCopyMode = _
DataGridViewClipboardCopyMode.EnableWithoutHeaderText
选中部分拷贝
[https://www.wendangku.net/doc/257335622.html,]
'選択されたセルをクリップボードにコピーする
Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
17.DataGridView粘贴
[https://www.wendangku.net/doc/257335622.html,]
'現在のセルのある行から下にペーストする
If DataGridView1.CurrentCell Is Nothing Then
Return
End If
'クリップボードの内容を取得して、行で分ける
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) Then
Return
End If
pasteText = pasteText.Replace(vbCrLf, vbLf)
pasteText = pasteText.Replace(vbCr, vbLf)
pasteText.TrimEnd(New Char() {vbLf})
Dim lines As String() = pasteText.Split(vbLf)
Dim isHeader As Boolean = True
For Each line As String In lines
'列ヘッダーならば飛ばす
If isHeader Then
isHeader = False
Else
'タブで分割
Dim vals As String() = line.Split(ControlChars.Tab)
'列数が合っているか調べる
If vals.Length - 1 <> DataGridView1.ColumnCount Then
Throw New ApplicationException("列数が違います。")
End If
Dim row As DataGridViewRow = DataGridView1.Rows(insertRowIndex)
'ヘッダーを設定
row.HeaderCell.Value = vals(0)
'各セルの値を設定
Dim i As Integer
For i = 0 To row.Cells.Count - 1
row.Cells(i).Value = vals((i + 1))
Next i
'次の行へ
insertRowIndex += 1
End If
Next line
18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息)
[https://www.wendangku.net/doc/257335622.html,]
'セルに表示するToolTipを設定する
DataGridView1(0, 0).ToolTipText = "このセルは変更できません"
'列ヘッダーに表示するToolTipを設定する
DataGridView1.Columns(0).ToolTipText = "この列には数字を入力できます"
'行ヘッダーに表示するToolTipを設定する
DataGridView1.Rows(0).HeaderCell.ToolTipText = "この行のセルは変更できません"
CellToolTipTextNeeded事件,在多个单元格使用相同的ToolTips的时候,可以用该事件,下例为显示当前单元格的行号和列号
[https://www.wendangku.net/doc/257335622.html,]
'CellToolTipTextNeededイベントハンドラ
Private Sub DataGridView1_CellToolTipTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewCellToolTipTextNeededEventArgs) _
Handles DataGridView1.CellToolTipTextNeeded
e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString()
DataGridView控件用法合集(四)
19. DataGridView中的ContextMenuStrip属性
20. DataGridView指定滚动框位置
21. DataGridView手动追加列
22. DataGridView全体分界线样式设置
23. DataGridView根据单元格属性更改显示内容
24. DataGridView新追加行的行高样式设置る
25. DataGridView新追加行单元格默认值设置
19. DataGridView中的ContextMenuStrip属性
[https://www.wendangku.net/doc/257335622.html,]
'DataGridViewのContextMenuStripを設定する
DataGridView1.ContextMenuStrip = Me.ContextMenuStrip1
'列のContextMenuStripを設定する
DataGridView1.Columns(0).ContextMenuStrip = Me.ContextMenuStrip2
'列ヘッダーのContextMenuStripを設定する
DataGridView1.Columns(0).HeaderCell.ContextMenuStrip = Me.ContextMenuStrip2
'行のContextMenuStripを設定する
DataGridView1.Rows(0).ContextMenuStrip = Me.ContextMenuStrip3
'セルのContextMenuStripを設定する
DataGridView1(1, 0).ContextMenuStrip = Me.ContextMenuStrip4
也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义[https://www.wendangku.net/doc/257335622.html,]
'CellContextMenuStripNeededイベントハンドラ
Private Sub DataGridView1_CellContextMenuStripNeeded( _
ByVal sender As Object, _
ByVal e As DataGridViewCellContextMenuStripNeededEventArgs) _
Handles DataGridView1.CellContextMenuStripNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
If e.RowIndex < 0 Then
'列ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = Me.ContextMenuStrip1
ElseIf e.ColumnIndex < 0 Then
'行ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = Me.ContextMenuStrip2
ElseIf TypeOf (dgv(e.ColumnIndex, e.RowIndex).Value) Is Integer Then 'セルが整数型のときに表示するContextMenuStripを変更する
e.ContextMenuStrip = Me.ContextMenuStrip3
End If
End Sub
20. DataGridView指定滚动框位置
[https://www.wendangku.net/doc/257335622.html,]
'先頭の行までスクロールする
DataGridView1.FirstDisplayedScrollingRowIndex = 0
'先頭の列までスクロールする
DataGridView1.FirstDisplayedScrollingColumnIndex = 0
21. DataGridView手动追加列
[https://www.wendangku.net/doc/257335622.html,]
'列が自動的に作成されないようにする
'データソースを設定する
DataGridView1.DataSource = BindingSource1
'DataGridViewTextBoxColumn列を作成する
Dim textColumn As New DataGridViewTextBoxColumn()
'データソースの"Column1"をバインドする
textColumn.DataPropertyName = "Column1"
'名前とヘッダーを設定する
https://www.wendangku.net/doc/257335622.html, = "Column1"
textColumn.HeaderText = "Column1"
'列を追加する
DataGridView1.Columns.Add(textColumn)
22. DataGridView全体分界线样式设置
[https://www.wendangku.net/doc/257335622.html,]
'DataGridViewの境界線を3Dにする
DataGridView1.BorderStyle = BorderStyle.Fixed3D
单元格上下左右分界线样式设置
[https://www.wendangku.net/doc/257335622.html,]
'セルの上と左を二重線のくぼんだ境界線にし、
'下と右を一重線のくぼんだ境界線にする
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble 23. DataGridView根据单元格属性更改显示内容
如下例,当该列是字符串时,自动转换文字大小写
[https://www.wendangku.net/doc/257335622.html,]
'CellFormattingイベントハンドラ
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルの列を確認
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
TypeOf e.Value Is String Then
'大文字にして表示する
Dim str As String = e.Value.ToString()
e.Value = str.ToUpper()
'フォーマットの必要がないことを知らせる
e.FormattingApplied = True
End If
End Sub
24. DataGridView新追加行的行高样式设置
行高设置
[https://www.wendangku.net/doc/257335622.html,]
'行テンプレートの高さを設定する
DataGridView1.RowTemplate.Height = 50
'行の最低の高さを設定する
DataGridView1.RowTemplate.MinimumHeight = 50
样式设置
'行テンプレートのセルスタイルの背景色を黄色にする
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow
25. DataGridView新追加行单元格默认值设置
[https://www.wendangku.net/doc/257335622.html,]
'DefaultValuesNeededイベントハンドラ
Private Sub DataGridView1_DefaultValuesNeeded(ByVal sender As Object, _
ByVal e As DataGridViewRowEventArgs) _
Handles DataGridView1.DefaultValuesNeeded
'セルの既定値を指定する
e.Row.Cells("Column1").Value = 0
e.Row.Cells("Column2").Value = "-"
End Sub
DataGridView中输入错误数据的处理(五)
26. DataGridView单元格数据错误标签表示
27. DataGridView单元格内输入值正确性判断
28. DataGridView单元格输入错误值事件的捕获
26. DataGridView单元格数据错误标签表示
https://www.wendangku.net/doc/257335622.html,]
'(0, 0)のセルにエラーアイコンを表示する
DataGridView1(0, 0).ErrorText = "セルの値を確認してください。"
'インデックスが3の行にエラーアイコンを表示する
DataGridView1.Rows(3).ErrorText = "負の値は入力できません。"
[C#]
//(0, 0)のセルにエラーアイコンを表示する
DataGridView1[0, 0].ErrorText = "セルの値を確認してください。";
//インデックスが3の行にエラーアイコンを表示する
DataGridView1.Rows[3].ErrorText = "負の値は入力できません。";
在大量单元格需要错误提示时,也可以用CellErrorTextNeeded、RowErrorTextNeeded事件[https://www.wendangku.net/doc/257335622.html,]
'CellErrorTextNeededイベントハンドラ
Private Sub DataGridView1_CellErrorTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewCellErrorTextNeededEventArgs) _
Handles DataGridView1.CellErrorTextNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルの値が負の整数であれば、エラーアイコンを表示する
Dim cellVal As Object = dgv(e.ColumnIndex, e.RowIndex).Value
If TypeOf cellVal Is Integer AndAlso CInt(cellVal) < 0 Then
e.ErrorText = "負の整数は入力できません。"
End Sub
'RowErrorTextNeededイベントハンドラ
Private Sub DataGridView1_RowErrorTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewRowErrorTextNeededEventArgs) _
Handles DataGridView1.RowErrorTextNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv("Column1", e.RowIndex).Value Is DBNull.Value AndAlso _
dgv("Column2", e.RowIndex).Value Is DBNull.Value Then
e.ErrorText = _
"少なくともColumn1とColumn2のどちらかには値を入力してください。"
End If
End Sub
[C#]
//CellErrorTextNeededイベントハンドラ
private void DataGridView1_CellErrorTextNeeded(object sender,
DataGridViewCellErrorTextNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//セルの値が負の整数であれば、エラーアイコンを表示する
object cellVal = dgv[e.ColumnIndex, e.RowIndex].Value;
if (cellVal is int && ((int)cellVal) < 0)
{
e.ErrorText = "負の整数は入力できません。";
}
}
//RowErrorTextNeededイベントハンドラ
private void DataGridView1_RowErrorTextNeeded(object sender,
DataGridViewRowErrorTextNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv["Column1", e.RowIndex].Value == DBNull.Value &&
dgv["Column2", e.RowIndex].Value == DBNull.Value)
{
e.ErrorText =
"少なくともColumn1とColumn2のどちらかには値を入力してください。";
}
}
27. DataGridView单元格内输入值正确性判断
[https://www.wendangku.net/doc/257335622.html,]
'CellValidatingイベントハンドラ
Private Sub DataGridView1_CellValidating(ByVal sender As Object, _
ByVal e As DataGridViewCellValidatingEventArgs) _
Handles DataGridView1.CellValidating
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
e.FormattedValue.ToString() = "" Then
'行にエラーテキストを設定
dgv.Rows(e.RowIndex).ErrorText = "値が入力されていません。"
'入力した値をキャンセルして元に戻すには、次のようにする
'キャンセルする
e.Cancel = True
End If
End Sub
'CellValidatedイベントハンドラ
Private Sub DataGridView1_CellValidated(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValidated
Dim dgv As DataGridView = CType(sender, DataGridView)
'エラーテキストを消す
dgv.Rows(e.RowIndex).ErrorText = Nothing
End Sub
[C#]
//CellValidatingイベントハンドラ
private void DataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&
e.FormattedValue.ToString() == "")
{
//行にエラーテキストを設定
dgv.Rows[e.RowIndex].ErrorText = "値が入力されていません。";
//入力した値をキャンセルして元に戻すには、次のようにする
//dgv.CancelEdit();
//キャンセルする
e.Cancel = true;
}
}
//CellValidatedイベントハンドラ
private void DataGridView1_CellValidated(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//エラーテキストを消す
dgv.Rows[e.RowIndex].ErrorText = null;
}
28. DataGridView单元格输入错误值事件的捕获
[https://www.wendangku.net/doc/257335622.html,]
'DataErrorイベントハンドラ
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
If Not (e.Exception Is Nothing) Then
MessageBox.Show(Me, _
String.Format("({0}, {1}) のセルでエラーが発生しました。" + _ vbCrLf + vbCrLf + "説明: {2}", _
e.ColumnIndex, e.RowIndex, e.Exception.Message), _
"エラーが発生しました", _
MessageBoxIcon.Error)
End If
End Sub
[C#]
//DataErrorイベントハンドラ
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
if (e.Exception != null)
{
MessageBox.Show(this,
string.Format("({0}, {1}) のセルでエラーが発生しました。\n\n説明: {2}", e.ColumnIndex, e.RowIndex, e.Exception.Message),
"エラーが発生しました",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
输入错误值时返回原先数据
[https://www.wendangku.net/doc/257335622.html,]
'DataErrorイベントハンドラ
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
e.Cancel = False
End Sub
[C#]
//DataErrorイベントハンドラ
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
e.Cancel = false;
}
DataGridView控件用法合集(六)
29. DataGridView行排序(点击列表头自动排序的设置)
30. DataGridView自动行排序(新追加值也会自动排序)
31. DataGridView自动行排序禁止情况下的排序
32. DataGridView指定列指定排序
29. DataGridView行排序(点击列表头自动排序的设置)
[https://www.wendangku.net/doc/257335622.html,]
'並び替えができないようにする
For Each c As DataGridViewColumn In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.NotSortable
Next c
30. DataGridView自动行排序(新追加值也会自动排序)
[https://www.wendangku.net/doc/257335622.html,]
'フォームのLoadイベントハンドラ
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim c As DataGridViewColumn
For Each c In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.Automatic
Next c
End Sub
'Button1のClickイベントハンドラ
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If DataGridView1.CurrentCell Is Nothing Then
Return
End If
'並び替える列を決める
Dim sortColumn As DataGridViewColumn = _
DataGridView1.CurrentCell.OwningColumn
'並び替えの方向(昇順か降順か)を決める
Dim sortDirection As https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection = _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Ascending
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
DataGridView1.SortedColumn.Equals(sortColumn) Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Ascending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Descending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Ascending) End If
'並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection)
End Sub
31. DataGridView自动行排序禁止情况下的排序
'ColumnHeaderMouseClickイベントハンドラ
Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, _
ByVal e As DataGridViewCellMouseEventArgs) _
Handles DataGridView1.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = _
DataGridView1.Columns(e.ColumnIndex)
If clickedColumn.SortMode <> DataGridViewColumnSortMode.Automatic Then Me.SortRows(clickedColumn, True)
End If
End Sub
'RowsAddedイベントハンドラ
Private Sub DataGridView1_RowsAdded(ByVal sender As Object, _
ByVal e As DataGridViewRowsAddedEventArgs) _
Handles DataGridView1.RowsAdded
Me.SortRows(DataGridView1.SortedColumn, False)
End Sub
'CellValueChangedイベントハンドラ
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
e.ColumnIndex = DataGridView1.SortedColumn.Index Then
End If
End Sub
'''
''' 指定された列を基準にして並び替えを行う
'''
''' 基準にする列
''' 並び替えの方向をトグルで変更する Private Sub SortRows(ByVal sortColumn As DataGridViewColumn, _
ByVal orderToggle As Boolean)
If sortColumn Is Nothing Then
Return
End If
'今までの並び替えグリフを消す
If sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic AndAlso _ Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
Not DataGridView1.SortedColumn.Equals(sortColumn) Then
DataGridView1.SortedColumn.HeaderCell.SortGlyphDirection = _
SortOrder.None
End If
'並び替えの方向(昇順か降順か)を決める
Dim sortDirection As https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection
If orderToggle Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Ascending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Descending) Else
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Descending, _
https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Ascending) End If
Dim sOrder As SortOrder = _
IIf(sortDirection = https://www.wendangku.net/doc/257335622.html,ponentModel.ListSortDirection.Ascending, _
SortOrder.Ascending, SortOrder.Descending)
'並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection)
If sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic Then '並び替えグリフを変更
sortColumn.HeaderCell.SortGlyphDirection = sOrder
End If
End Sub
[C#]
//フォームのLoadイベントハンドラ
private void Form1_Load(object sender, EventArgs e)
{
//イベントハンドラの追加
DataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(
DataGridView1_RowsAdded);
DataGridView1.CellValueChanged += new DataGridViewCellEventHandler(
DataGridView1_CellValueChanged);
DataGridView1_ColumnHeaderMouseClick);
}
//ColumnHeaderMouseClickイベントハンドラ
private void DataGridView1_ColumnHeaderMouseClick(object sender,
DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn clickedColumn = DataGridView1.Columns[e.ColumnIndex]; if (clickedColumn.SortMode != DataGridViewColumnSortMode.Automatic)
this.SortRows(clickedColumn, true);
}
//RowsAddedイベントハンドラ
private void DataGridView1_RowsAdded(object sender,
DataGridViewRowsAddedEventArgs e)
{
this.SortRows(DataGridView1.SortedColumn, false);
}
//CellValueChangedイベントハンドラ
private void DataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
if (DataGridView1.SortedColumn != null &&
e.ColumnIndex == DataGridView1.SortedColumn.Index)
this.SortRows(DataGridView1.SortedColumn, false);
}
///
/// 指定された列を基準にして並び替えを行う
///
/// 基準にする列
/// 並び替えの方向をトグルで変更する private void SortRows(DataGridViewColumn sortColumn, bool orderToggle)
{
if (sortColumn == null)
return;
//今までの並び替えグリフを消す
if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic &&
DataGridView1.SortedColumn != null &&
!DataGridView1.SortedColumn.Equals(sortColumn))
{
DataGridView1.SortedColumn.HeaderCell.SortGlyphDirection =
SortOrder.None;
}
//並び替えの方向(昇順か降順か)を決める
ListSortDirection sortDirection;
if (orderToggle)
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Descending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
}
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Descending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
SortOrder sortOrder =
sortDirection == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
//並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection);
if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic) {
//並び替えグリフを変更
sortColumn.HeaderCell.SortGlyphDirection = sortOrder;
}
}
32. DataGridView指定列指定排序
[https://www.wendangku.net/doc/257335622.html,]
'DataGridView1にバインドされているDataTableを取得
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
'DataViewを取得
Dim dv As DataView = dt.DefaultView
'Column1とColumn2で昇順に並び替える
dv.Sort = "Column1, Column2 ASC"
'2つの列のヘッダーに並び替えグリフを表示する
DataGridView1.Columns("Column1").HeaderCell.SortGlyphDirection = _
SortOrder.Ascending
DataGridView1.Columns("Column2").HeaderCell.SortGlyphDirection = _
SortOrder.Ascending
[C#]
//DataGridView1にバインドされているDataTableを取得
DataTable dt = (DataTable)DataGridView1.DataSource;
//DataViewを取得
DataView dv = dt.DefaultView;
//Column1とColumn2で昇順に並び替える
dv.Sort = "Column1, Column2 ASC";
//2つの列のヘッダーに並び替えグリフを表示する
DataGridView1.Columns["Column1"].HeaderCell.SortGlyphDirection =
SortOrder.Ascending;
DataGridView1.Columns["Column2"].HeaderCell.SortGlyphDirection =
SortOrder.Ascending;
DataGridView控件用法合集(七)
33. DataGridView单元格样式设置
34. DataGridView文字表示位置的设定
35. DataGridView单元格内文字列换行
36. DataGridView单元格DBNull值表示的设定
37. DataGridView单元格样式格式化
38. DataGridView指定单元格颜色设定
39. DataGridView单元格文字字体设置
33. DataGridView单元格样式设置
指定行列的样式设定
[https://www.wendangku.net/doc/257335622.html,]
'インデックス0の列のセルの背景色を水色にする
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Aqua
'インデックス0の行のセルの背景色を薄い灰色にする
DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.LightGray
[C#]
//インデックス0の列のセルの背景色を水色にする
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;
//インデックス0の行のセルの背景色を薄い灰色にする
DataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;
奇数行样式设定
[https://www.wendangku.net/doc/257335622.html,]
'奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow [C#]
//奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow; 行,列表头部的样式设定
[https://www.wendangku.net/doc/257335622.html,]
'列ヘッダーの背景色をアイボリーにする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory
'行ヘッダーの背景色をライムにする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime
[C#]
//列ヘッダーの背景色をアイボリーにする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory;
//行ヘッダーの背景色をライムにする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime;
样式的优先顺序
一般单元格的样式优先顺位
DataGridViewCell.Style
DataGridViewRow.DefaultCellStyle
DataGridView.AlternatingRowsDefaultCellStyle
DataGridView.RowsDefaultCellStyle
DataGridViewColumn.DefaultCellStyle
DataGridView.DefaultCellStyle
表头部的样式优先顺位
DataGridViewCell.Style
DataGridView.RowHeadersDefaultCellStyle
DataGridView.ColumnHeadersDefaultCellStyle
DataGridView.DefaultCellStyle
下例说明
[https://www.wendangku.net/doc/257335622.html,]
'1列目を水色にする
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Aqua
'全ての列の背景色を黄色にする
'奇数行を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow '3行目をピンクにする
DataGridView1.Rows(2).DefaultCellStyle.BackColor = Color.Pink
'自身のセルスタイルと継承されたセルスタイルの背景色を取得する
'1列目のセルスタイル
'"[Aqua]"と"[Aqua]"と表示される
Console.WriteLine(DataGridView1.Columns(0).DefaultCellStyle.BackColor) Console.WriteLine(DataGridView1.Columns(0).InheritedStyle.BackColor)
'1行目のセルスタイル
'"[Empty]"と"[Yellow]"と表示される
Console.WriteLine(DataGridView1.Rows(0).DefaultCellStyle.BackColor) Console.WriteLine(DataGridView1.Rows(0).InheritedStyle.BackColor)
'2行目のセルスタイル
'"[Empty]"と"[GreenYellow]"と表示される
Console.WriteLine(DataGridView1.Rows(1).DefaultCellStyle.BackColor) Console.WriteLine(DataGridView1.Rows(1).InheritedStyle.BackColor)
'3行目のセルスタイル
'"[Pink]"と"[Pink]"と表示される
Console.WriteLine(DataGridView1.Rows(2).DefaultCellStyle.BackColor) Console.WriteLine(DataGridView1.Rows(2).InheritedStyle.BackColor)
'(0, 3)のセルスタイル
'"[Empty]"と"[Pink]"と表示される
Console.WriteLine(DataGridView1(0, 2).Style.BackColor)
Console.WriteLine(DataGridView1(0, 2).InheritedStyle.BackColor)
[C#]
//1列目を水色にする
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;
//全ての列の背景色を黄色にする
DataGridView1.RowsDefaultCellStyle.BackColor = Color.Yellow;
//奇数行を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow; //3行目をピンクにする
DataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Pink;
//自身のセルスタイルと継承されたセルスタイルの背景色を取得する
//1列目のセルスタイル
//"[Aqua]"と"[Aqua]"と表示される
Console.WriteLine(DataGridView1.Columns[0].DefaultCellStyle.BackColor); Console.WriteLine(DataGridView1.Columns[0].InheritedStyle.BackColor);
//1行目のセルスタイル
//"[Empty]"と"[Yellow]"と表示される
Console.WriteLine(DataGridView1.Rows[0].DefaultCellStyle.BackColor); Console.WriteLine(DataGridView1.Rows[0].InheritedStyle.BackColor);
//2行目のセルスタイル
//"[Empty]"と"[GreenYellow]"と表示される
Console.WriteLine(DataGridView1.Rows[1].DefaultCellStyle.BackColor); Console.WriteLine(DataGridView1.Rows[1].InheritedStyle.BackColor);
//3行目のセルスタイル
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);
在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控件用法合集(一) 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指定单元格颜色设定
vb6.0中DataGrid控件的使用 https://www.wendangku.net/doc/257335622.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. 使用“属性页”对话框来设置该控件的适当的属性,将该网格配置为所需的外观和行为。 在运行时更改显示的数据
使用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 的记录。
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; }
简单的DataGrid控件在
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的大部分主要功能,而且很多难点都可以在里面找到解决方案。 由于涉及的应用比较多,所以篇幅会很长。但可以确保各个版块相互独立,总共4个部分 1.数据绑定 2.DataGrid的增改删功能 3.DataGrid的分页实现 4.DataGrid的样式设计 先上一张截图,让你大概知道自己需要的功能是否在这张图里有所实现。 PS:使用技术:WPF+https://www.wendangku.net/doc/257335622.html, Entity Framework
1.数据绑定(涉及DataGrid绑定和Combox绑定) 在DataGrid中同时包含“自动生成列”与“用户自定义列”由属性AutoGenerateColumns控制。 默认情况下,DataGrid将根据数据源自动生成列。下图列出了生成的列类型。 如果AutoGenerateColumns="True",我们只需要如下几行代码
WPF中DataGrid的使用 DataGrid是WPF中的数据显示控件,相当于Winform中的DataGridView。但是两者之间的用法确存在一些差异。在文档中,如果利用两者的不同之处可以更加清楚的描述好DataGrid的使用,我将采用该种方法。好了我们首先看一下如何为DataGrid指定数据源吧! 我们知道在Winform中DataGridView的数据源可以是DataTable,DataView,List
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新手介绍了如何使用.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、如果连接工作正常,点击确定返回向导窗口,然后点击下一步继续;
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)
vb的datagrid控件的使用(二) 时间:2007-05-05 创建Northwind 的OLE DB 数据链接 访问数据的一个重要步骤是为想要访问的每个数据库都创建一个OLE DB数据源。下面的步骤为Visual Basic 所提供的Nwind.mdb (Northwind) 数据库创建这样一个对象。这个数据源被用于Visual Basic 文档所提供的一些示例过程。在一个计算机上只需要创建一次OLE DB数据源。 要创建Northwind 的OLE DB 数据源 1. 打开Windows Explorer或Windows NT Explorer。 2. 打开您想要创建OLE DB 数据源的目录。在该示例中,打开ProgramFiles、Microsoft Visual Studio和VB98。 3. 右键单击Explorer 的右边窗格,然后单击上下文菜单上的“新建”。从文件类型列表中单击“Microsoft 数据链接”。 4. 重命名新文件Northwind.MDL。 5. 右键单击文件并单击上下文菜单上的“属性”,以显示“Northwind.MDLProperties”对话框。 6. 单击“连接”选项卡。 7. 单击“提供方”框并选择“Microsoft Jet 3.51 OLE DB Provider”。 8. 在Data Source 框中输入nwind.mdb文件的路径。 9. 单击“测试连接”,检测连接。 10. 如果连接通过,单击“确定”。 注意也可以通过在“控制面板”中单击“数据链接”图标创建一个OLE DB数据源。在“管理数据链接文件”对话框中,单击“新建”创建一个新的数据源。 使用DataGrid 和ADO Data控件创建一个简单的数据库应用程序 只使用一个DataGrid 和一个ADO Data 控件,可以创建一个允许最终用户阅读和写入记录集的数据库应用程序。 要使用ADO 数据控件来创建一个简单的数据库应用程序 1. 为Northwind 数据库创建一个OLE DB 数据源。如果还没有创建数据源,请按照“创建Northwind 的OLE DB Data Link”中的步骤操作。 2. 在Visual Basic 中创建一个新的标准的EXE 工程。如果DataGrid 控件不在“工具箱”中,则用右键单击“工具箱”,然后使用“部件”对话框来添加控件。同时也载入ADO 控件。 3. 在空窗体上各放置控件的一个实例。 4. 将ADO 控件的ConnectionString 属性设置为Northwind 的数据源。单击并选定该ADO Data 控件,并按F4 键出现“属性”窗口。单击“ConnectionString”,然后单击OLE DB File。单击Northwind 的数据源。 5. 设置ADO 控件的RecordSource 属性。在“属性”窗口中,单击“记录源”并输入一条SQL 语句来填充DataGrid 控件。在本例中,输入“Select * From Products”。 6. 将DataGrid 控件的DataSource 属性设置为这个ADO Data 控件。单击并选定该DataGrid 控件。在其“属性”窗口中,单击“数据源”将出现一个包含所有数据控件的下拉列表——在
Winform下DataGridView控件自定义列System.Windows.Forms.DataGridView控件是net下,数据显示使用最多的控件之一,但是Datagridviewk控件列类型却仅仅只有6中 分别是button 、checkbox、combobox、image、link、textbox 等6种常见类型。这很难满足我们日常开发需要。如果需要复杂的应用,要么找第三方控件,要么只能自己开发。而功能强大的第三方控件往往是需要付费的。但我们开发需要的很可能只是简单的功能,如果为了某个简单功能而专门购买一个控件对于个人来说有些得不偿失。 那么我们只剩下自己开发一途。幸运的是DataGridView控件容许我们进行二次开发,可以自定义我们需要的控件列。下图就是自定义日期输入自定义列,通过下面的例子,你完全可以开发出自己需要的功能列。下面给出https://www.wendangku.net/doc/257335622.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"; }
〔DataGrid控件〕 在三种控件当中,DataGrid是迄今为止功能最为丰富的,但也是最不灵活的控件。这种在输出HTML时不够灵活的特点是因为它最初就是被设计成以表格的形式输出数据。每一条记录输出时会建立一对