文档库 最新最全的文档下载
当前位置:文档库 › DataGridView控件用法合集11

DataGridView控件用法合集11

DataGridView控件用法合集11
DataGridView控件用法合集11

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行目のセルスタイル

微软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指定单元格颜色设定

vb6.0中DataGrid控件的使用

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. 使用“属性页”对话框来设置该控件的适当的属性,将该网格配置为所需的外观和行为。 在运行时更改显示的数据

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 的记录。

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; }

简单的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.wendangku.net/doc/257335622.html, Entity Framework

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

WPF中DataGrid的使用

WPF中DataGrid的使用 DataGrid是WPF中的数据显示控件,相当于Winform中的DataGridView。但是两者之间的用法确存在一些差异。在文档中,如果利用两者的不同之处可以更加清楚的描述好DataGrid的使用,我将采用该种方法。好了我们首先看一下如何为DataGrid指定数据源吧! 我们知道在Winform中DataGridView的数据源可以是DataTable,DataView,List等,但是在WPF中DataGrid 的数据源不能直接为DataTable。作为DataGrid的数据源的对象必须实现了IEnumerable接口的,至于你们是否怀疑DataGrid的数据源真的不能直接指定为DataTable?那最好是自己去尝试一下。因为求知就得如此。我是试过了哈!如果你真的要将DataTable指定给DataGrid。那么你可以采用以下方法:this.dataGrid.ItemSource = dt.DefaultView;这里的dt是你创建的DataTable对象。你注意到了吗?先前我们使用的诸如DataGridView,ComboBox,Web中的GridView等数据显示控件在指定数据源时都是为其属性DataSource指定数据源对象。但是WPF中的DataGrid却不是这样,我开始接触的时候按照自己的思维方式去找寻DataSource属性,可未成功!查阅资料才知道是ItemSource属性。所以请注意了! 我们在使用DataGrid控件时,可以直接将数据源对象指定给DataGrid的ItemSource属性。此时数据显示将按照数据源的数据结构进行数据显示。如果你需要根据你自己定义的方式显示数据,此时需要借助于代码定义样式了!DataGrid的整体外观我们可以通过设置DataGrid的属性来体现,也可以通过Style来体现。如利用DataGrid 的HeadersVisibility设置头或列是否显示,该属性有三个值,分别的含义是:None 表示列头和行头都不显示;All 表示列头和行头都显示;Row表示行头显示;Column 表示列头显示;利用DataGrid的RowBackgroud属性设置行的背景色等等。我们也可以利用设置DataGrid的Style来控制DataGrid的外观样式。如利用DataGrid.ColumnHeaderStyle来设置DataGrid的列头显示样式,示例代码如下: 以上代码分别对DataGrid的列头的背景色、前景色和字体做了设置。其中在设置背景色时,利用了(LinearGradientBrush)使其背景色呈渐变效果。 利用DataGrid.RowHeaderStyle来设置DataGrid的行头显示样式,示例代码如下:

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

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)

vb的datagrid控件的使用(二)

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 控件。在其“属性”窗口中,单击“数据源”将出现一个包含所有数据控件的下拉列表——在

DataGridView自定义列

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控件〕 在三种控件当中,DataGrid是迄今为止功能最为丰富的,但也是最不灵活的控件。这种在输出HTML时不够灵活的特点是因为它最初就是被设计成以表格的形式输出数据。每一条记录输出时会建立一对标签,而每个字段的值输出时则建立一对标签。 DataGrid含有几个属性可以提高其可用性。如,通过设置DataGrid的AllowSorting属性为true,并加入少量代码,DataGrid就具备了按不同字段排序的功能。此外,设定相关属性来实现分页以及单条记录编辑的功能更加增强了DataGrid的可用性。 除了在可用性方面的支持以外,DataGrid同时也相当节省开发时间。使用DataGrid在WEB 页面上显示数据只需要两行代码。一行用来设定与DataGrid绑定的数据源(DataSource),另一条则用来执行绑定命令(DataBind())。当然,在Repeater中实现这样的功能并非不可能,只是,相比较使用DataGrid而言,你需要花费相当多的时间和精力来实现这些功能。 尽管DataGrid有这样那样令人印象深刻的优点,它的两个缺点也同样不能忽视。首先,如前所述,DataGrid在个性化输出数据方面功能有限。当然,你可以定制字体、颜色以及线条宽度等等,但它始终只能是HTML表格。 每个在DataGrid中的列都是DataGridColumn类的一个实例。有五种DataGrid列的形式: ·BoundColumn ·ButtonColumn ·EditColumn ·HyperLinkColumn ·TemplateColumn 每种类型都会以一种方式允许页面访问与DataGrid进行交互。例如,BoundColumn将DataSource的字段值显示为纯文本;而HyperLinkColumn则将之显示为一个超级链接。另外,开发者可以通过写一个继承自DataGridColumn的自定义类来定制DataGrid列的样式。 尽管DataGrid具有这么多的增强可用性的属性,却仍然显得死板而不够灵活。这是因为,不论什么样的属性,都需要对DataGrid所生成的表格进行相关的设置而生效。这无疑会使表格变得臃肿而失去灵活性。例如,DataGridColumn的设置会对表格的每一行的相应列生效。DataGrid的这种局限性阻碍了更有创意地显示数据。比如,你希望每五条记录被显示在一行,或根本不想要表格来显示数据,你将不得不放弃使用DataGrid。 DataGrid的第二个缺陷是它的性能。在三种数据控件中,DataGrid是相对性能最差的。由DataGrid所生成的ViewState将会相当庞大,特别是在DataGrid含有较多的行时。当然,你也可以关闭ViewState功能,但代价是你将不能使用排序、分页以及记录编辑等功能。 为了测量DataGrid的性能,我使用了微软的Web Application Stress Tool (WAST)。精确的测试条件设定以及测试用代码将会在本文的结尾给出。

相关文档