DataGridView控件用法合集(四)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第四部分。
19. DataGridView中的ContextMenuStrip属性
20. DataGridView指定滚动框位置
21. DataGridView手动追加列
22. DataGridView全体分界线样式设置
23. DataGridView根据单元格属性更改显示内容
24. DataGridView新追加行的行高样式设置る
25. DataGridView新追加行单元格默认值设置
19. DataGridView中的ContextMenuStrip属性
[VB.NET]
'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
[C#]
//DataGridViewのContextMenuStripを設定する
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
//列のContextMenuStripを設定する
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
//列ヘッダーのContextMenuStripを設定する
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
//行のContextMenuStripを設定する
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
//セルのContextMenuStripを設定する
DataGridView1[0, 1].ContextMenuStrip = this.ContextMenuStrip4;
也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义
[VB.NET]
'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
[C#]
//CellContextMenuStripNeededイベントハンドラ
private void DataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
//列ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
//行ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
//セルが整数型のときに表示するContextMenuStripを変更する
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
20. DataGridView指定滚动框位置
[VB.NET]
'先頭の行までスクロールする
DataGridView1.FirstDisplayedScrollingRowIndex = 0
'先頭の列までスクロールする
DataGridView1.FirstDisplayedScrollingColumnIndex = 0
[C#]
//先頭の行までスクロールする
DataGridView1.FirstDisplayedScrollingRowIndex = 0;
//先頭の列までスクロールする
DataGridView1.FirstDisplayedScrollingColumnIndex = 0;
21. DataGridView手动追加列
[VB.NET]
'列が自動的に作成されないようにする
DataGridView1.AutoGenerateColumns = False
'データソースを設定する
DataGridView1.DataSource = BindingSource1
'DataGridViewTextBoxColumn列を作成する
Dim textColumn As New DataGridViewTextBoxColumn()
'データソースの"Column1"をバインドする
textColumn.DataPropertyName = "Column1"
'名前とヘッダーを設定する
textColumn.Name = "Column1"
textColumn.HeaderText = "Column1"
'列を追加する
DataGridView1.Columns.Add(textColumn)
[C#]
//列が自動的に作成されないようにする
DataGridView1.AutoGenerateColumns = false;
//データソースを設定する
DataGridView1.DataSource = BindingSource1;
//DataGridViewTextBoxColumn列を作成する
DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
//データソースの"Column1"をバインドする
textColumn.DataPropertyName = "Column1";
//名前とヘッダーを設定する
textColumn.Name = "Column1";
textColumn.HeaderText = "Column1";
//列を追加する
DataGridView1.Columns.Add(textColumn);
22. DataGridView全体分界线样式设置
[VB.NET]
'DataGridViewの境界線を3Dにする
DataGridView1.BorderStyle = BorderStyle.Fixed3D
[C#]
//DataGridViewの境界線を3Dにする
DataGridView1.BorderStyle = BorderStyle.Fixed3D;
单元格上下左右分界线样式设置
[VB.NET]
'セルの上と左を二重線のくぼんだ境界線にし、
'下と右を一重線のくぼんだ境界線にする
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble
[C#]
//セルの上と左を二重線のくぼんだ境界線にし、
//下と右を一重線のくぼんだ境界線にする
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble;
23. DataGridView根据单元格属性更改显示内容
如下例,当该列是字符串时,自动转换文字大小写
[VB.NET]
'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
[C#]
//CellFormattingイベントハンドラ
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//セルの列を確認
if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)
{
//大文字にして表示する
string str = e.Value.ToString();
e.Value = str.ToUpper();
//フォーマットの必要がないことを知らせる
e.FormattingApplied = true;
}
}
24. DataGridView新追加行的行高样式设置
行高设置
[VB.NET]
'行テンプレートの高さを設定する
DataGridView1.RowTemplate.Height = 50
'行の最低の高さを設定する
DataGridView1.RowTemplate.MinimumHeight = 50
[C#]
//行テンプレートの高さを設定する
DataGridView1.RowTemplate.Height = 50;
//行の最低の高さを設定する
DataGridView1.RowTemplate.MinimumHeight = 50;
样式设置
[VB.NET]
'行テンプレートのセルスタイルの背景色を黄色にする
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow
[C#]
//行テンプレートのセルスタイルの背景色を黄色にする
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow;
25. DataGridView新追加行单元格默认值设置
[VB.NET]
'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
[C#]
//DefaultValuesNeededイベントハンドラ
private void DataGridView1_DefaultValuesNeeded(object sender,
DataGridViewRowEventArgs e)
{
//セルの既定値を指定する
e.Row.Cells["Column1"].Value = 0;
e.Row.Cells["Column2"].Value = "-";
}
DataGridView控件用法合集(六)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第六部分。
DataGridView排序
29. DataGridView行排序(点击列表头自动排序的设置)
30. DataGridView自动行排序(新追加值也会自动排序)
31. DataGridView自动行排序禁止情况下的排序
32. DataGridView指定列指定排序
29. DataGridView行排序(点击列表头自动排序的设置)
[VB.NET]
'並び替えができないようにする
For Each c As DataGridViewColumn In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.NotSortable
Next c
[C#]
//並び替えができないようにする
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.NotSortable;
30. DataGridView自动行排序(新追加值也会自动排序)
[VB.NET]
'フォームの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 System.ComponentModel.ListSortDirection = _
System.ComponentModel.ListSortDirection.Ascending
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
DataGridView1.SortedColumn.Equals(sortColumn) Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Ascending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
'並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection)
End Sub
[C#]
//フォームのLoadイベントハンドラ
private void Form1_Load(object sender, EventArgs e)
{
//自動的に並び替えられるようにする
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.Automatic;
}
//Button1のClickイベントハンドラ
private void Button1_Click(object sender, EventArgs e)
{
if (DataGridView1.CurrentCell == null)
return;
//並び替える列を決める
DataGridViewColumn sortColumn = DataGridView1.CurrentCell.OwningColumn;
//並び替えの方向(昇順か降順か)を決める
ListSortDirection sortDirection = ListSortDirection.Ascending;
if (DataGridView1.SortedColumn != null &&
DataGridView1.SortedColumn.Equals(sortColumn))
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Ascending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
//並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection);
}
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
Me.SortRows(DataGridView1.SortedColumn, False)
End If
End Sub
''' <summary>
''' 指定された列を基準にして並び替えを行う
''' </summary>
''' <param name="sortColumn">基準にする列</param>
''' <param name="orderToggle">並び替えの方向をトグルで変更する</param>
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 System.ComponentModel.ListSortDirection
If orderToggle Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Ascending, _
System.ComponentModel.ListSortDirection.Descending)
Else
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
Dim sOrder As SortOrder = _
IIf(sortDirection = System.ComponentModel.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 += new DataGridViewCellMouseEventHandler(
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);
}
/// <summary>
/// 指定された列を基準にして並び替えを行う
/// </summary>
/// <param name="sortColumn">基準にする列</param>
/// <param name="orderToggle">並び替えの方向をトグルで変更する</param>
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;
}
else
{
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指定列指定排序
[VB.NET]
'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控件用法合集(七)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第七部分。
DataGridView样式
33. DataGridView单元格样式设置
34. DataGridView文字表示位置的设定
35. DataGridView单元格内文字列换行
36. DataGridView单元格DBNull值表示的设定
37. DataGridView单元格样式格式化
38. DataGridView指定单元格颜色设定
39. DataGridView单元格文字字体设置
40. DataGridView根据单元格值设定单元格样式
33. DataGridView单元格样式设置
指定行列的样式设定
[VB.NET]
'インデックス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;
奇数行样式设定
[VB.NET]
'奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow
[C#]
//奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;
行,列表头部的样式设定
[VB.NET]
'列ヘッダーの背景色をアイボリーにする
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
下例说明
[VB.NET]
'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行目のセルスタイル
'"[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行目のセルスタイル
//"[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);
复数行列的样式设定
[VB.NET]
'奇数列の背景色を変更する
'効率的な方法
Dim cellStyle As New DataGridViewCellStyle()
cellStyle.BackColor = Color.Yellow
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle = cellStyle
End If
Next i
'非効率的な方法
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle.BackColor = Color.Yellow
End If
Next i
[C#]
//奇数列の背景色を変更する
//効率的な方法
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.BackColor = Color.Yellow;
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle = cellStyle;
}
//非効率的な方法
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle.BackColor = Color.Yellow;
}
34. DataGridView文字表示位置的设定
单元格的设定
[VB.NET]
'"Column1"列のセルのテキストの配置を上下左右とも中央にする
DataGridView1.Columns("Column1").DefaultCellStyle.Alignment = _
DataGridViewContentAlignment.MiddleCenter
[C#]
//"Column1"列のセルのテキストの配置を上下左右とも中央にする
DataGridView1.Columns["Column1"].DefaultCellStyle.Alignment =
DataGridViewContentAlignment.MiddleCenter;
表头的设定
[VB.NET]
'"Column1"列のヘッダーのテキストの配置を上下左右とも中央にする
DataGridView1.Columns("Column1").HeaderCell.Style.Alignment = _
DataGridViewContentAlignment.MiddleCenter
[C#]
//"Column1"列のヘッダーのテキストの配置を上下左右とも中央にする
DataGridView1.Columns["Column1"].HeaderCell.Style.Alignment =
DataGridViewContentAlignment.MiddleCenter;
35. DataGridView单元格内文字列换行
[VB.NET]
'"Column1"列のセルのテキストを折り返して表示する
DataGridView1.Columns("Column1").DefaultCellStyle.WrapMode = _
DataGridViewTriState.True
'ヘッダーも折り返して表示するなら、次のようにする
DataGridView1.Columns("Column1").HeaderCell.Style.WrapMode = _
DataGridViewTriState.True
[C#]
//"Column1"列のセルのテキストを折り返して表示する
DataGridView1.Columns["Column1"].DefaultCellStyle.WrapMode =
DataGridViewTriState.True;
//ヘッダーも折り返して表示するなら、次のようにする
DataGridView1.Columns["Column1"].HeaderCell.Style.WrapMode =
DataGridViewTriState.True;
36. DataGridView单元格DBNull值表示的设定
[VB.NET]
DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)"
[C#]
DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)";
单元格内NullValue属性设定的值输入,表示单元格内为Null值
[VB.NET]
DataGridView1.DefaultCellStyle.NullValue = "-"
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X"
[C#]
DataGridView1.DefaultCellStyle.NullValue = "-";
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X";
37. DataGridView单元格样式格式化
[VB.NET]
'列のセルのテキストの書式を地域通貨として指定する
DataGridView1.Columns(0).DefaultCellStyle.Format = "c"
DataGridView1.Columns(1).DefaultCellStyle.Format = "c"
'2列目のカルチャを変更する
DataGridView1.Columns(1).DefaultCellStyle.FormatProvider = _
New System.Globalization.CultureInfo("en-US")
[C#]
//列のセルのテキストの書式を地域通貨として指定する
DataGridView1.Columns[0].DefaultCellStyle.Format = "c";
DataGridView1.Columns[1].DefaultCellStyle.Format = "c";
//2列目のカルチャを変更する
DataGridView1.Columns[1].DefaultCellStyle.FormatProvider =
new System.Globalization.CultureInfo("en-US");
Format的参数一览(整数)
書式
説明
値が"123456"の時
書式なし
123456
C
通貨
/123,456
D
10進数
123456
E
指数
1.234560E+005
F
固定小数点
123456.00
G
一般
123456
N
数値
123,456.00
P
パーセント
12,345,600.00%
R
ラウンドトリップ
(エラーが出る)
X
16進数
1E240
0
123456
00000000
00123456
########
123456
#,##0
123,456
%0
%12345600
00.000E0
12.346E4
プラス#;マイナス#;ゼロ
プラス123456
iの値は「#」です。
iの値は「123456」です
Format的参数一览(小数)
書式
説明
値が"1.23456789"の時
書式なし
1.23456789
C
通貨
/1
D
10進数
(エラーが出る)
E
指数
1.234568E+000
F
固定小数点
1.23
G
一般
1.23456789
N
数値
1.23
P
パーセント
123.46%
R
ラウンドトリップ
1.23456789
X
16進数
(エラーが出る)
00.0000000000
01.2345678900
##.##########
1.23456789
#,##0.000
1.235
%0.##
%123.46
00.000E0
12.346E-1
プラス#;マイナス#;ゼロ
プラス1.23
dの値は「#.##」です。
dの値は「1.23」です。
38. DataGridView指定单元格颜色设定
光标下的单元格颜色自动变换
[VB.NET]
'DataGridView1のCellMouseEnterイベントハンドラ
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを変更する
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Red
End If
End Sub
'DataGridView1のCellMouseLeaveイベントハンドラ
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを元に戻す
'セルスタイルを削除するなら、nullを設定してもよい
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Empty
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Empty
End If
End Sub
[C#]
//DataGridView1のCellMouseEnterイベントハンドラ
private void DataGridView1_CellMouseEnter(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを変更する
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
}
}
//DataGridView1のCellMouseLeaveイベントハンドラ
private void DataGridView1_CellMouseLeave(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを元に戻す
//セルスタイルを削除するなら、nullを設定してもよい
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Empty;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Empty;
}
}
表头部单元格颜色设定
[VB.NET]
'列ヘッダーの背景色を黄色にする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow
'行ヘッダーの背景色を黄緑色にする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen
'左上隅のヘッダーセルの背景色を青にする
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue
[C#]
//列ヘッダーの背景色を黄色にする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;
//行ヘッダーの背景色を黄緑色にする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen;
//左上隅のヘッダーセルの背景色を青にする
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue;
39. DataGridView单元格文字字体设置
光标下单元格字体设置为粗体
[VB.NET]
'デフォルトのセルスタイル
Private defaultCellStyle As DataGridViewCellStyle
'マウスポインタの下にあるセルのセルスタイル
Private mouseCellStyle As DataGridViewCellStyle
'フォームのLoadイベントハンドラ
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'デフォルトのセルスタイルの設定
Me.defaultCellStyle = New DataGridViewCellStyle()
'現在のセルのセルスタイルの設定
Me.mouseCellStyle = New DataGridViewCellStyle()
Me.mouseCellStyle.Font = New Font(DataGridView1.Font, _
DataGridView1.Font.Style Or FontStyle.Bold)
End Sub
'DataGridView1のCellMouseEnterイベントハンドラ
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを変更する
dgv(e.ColumnIndex, e.RowIndex).Style = Me.mouseCellStyle
End If
End Sub
'DataGridView1のCellMouseLeaveイベントハンドラ
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを元に戻す
'セルスタイルを削除するなら、nullを設定してもよい
dgv(e.ColumnIndex, e.RowIndex).Style = Me.defaultCellStyle
End If
End Sub
[C#]
//デフォルトのセルスタイル
private DataGridViewCellStyle defaultCellStyle;
//マウスポインタの下にあるセルのセルスタイル
private DataGridViewCellStyle mouseCellStyle;
//フォームのLoadイベントハンドラ
private void Form1_Load(object sender, EventArgs e)
{
//デフォルトのセルスタイルの設定
this.defaultCellStyle = new DataGridViewCellStyle();
//現在のセルのセルスタイルの設定
this.mouseCellStyle = new DataGridViewCellStyle();
this.mouseCellStyle.Font = new Font(DataGridView1.Font,
DataGridView1.Font.Style | FontStyle.Bold);
}
//DataGridView1のCellEnterイベントハンドラ
private void DataGridView1_CellEnter(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを変更する
dgv[e.ColumnIndex, e.RowIndex].Style = this.mouseCellStyle;
}
}
//DataGridView1のCellLeaveイベントハンドラ
private void DataGridView1_CellLeave(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを元に戻す
//セルスタイルを削除するなら、nullを設定してもよい
dgv[e.ColumnIndex, e.RowIndex].Style = this.defaultCellStyle;
}
}
40. DataGridView根据单元格值设定单元格样式
单元格负数情况下显示黄色,0的情况下显示红色
[VB.NET]
'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 Integer Then
Dim val As Integer = CInt(e.Value)
'セルの値により、背景色を変更する
If val < 0 Then
e.CellStyle.BackColor = Color.Yellow
Else If val = 0 Then
e.CellStyle.BackColor = Color.Red
End If
End If
End Sub
[C#]
//CellFormattingイベントハンドラ
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//セルの列を確認
if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is int)
{
int val = (int)e.Value;
//セルの値により、背景色を変更する
if (val < 0)
{
e.CellStyle.BackColor = Color.Yellow;
}
else if (val == 0)
{
e.CellStyle.BackColor = Color.Red;
}
}
}
DataGridView控件用法合集(八)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第八部分。
DataGridView Owner描画
41. DataGridView设置单元格背景颜色
42. DataGridView行样式描画
43. DataGridView显示行号
44. DataGridView焦点所在单元格焦点框不显示的设定
41. DataGridView设置单元格背景颜色
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のセルで、背景を描画する時
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'選択されているか調べ、色を決定する
'bColor1が開始色、bColor2が終了色
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.CellStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.CellStyle.BackColor
bColor2 = Color.LemonChiffon
End If
'グラデーションブラシを作成
Dim b As New System.Drawing.Drawing2D.LinearGradientBrush( _
e.CellBounds, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
Try
'セルを塗りつぶす
e.Graphics.FillRectangle(b, e.CellBounds)
Finally
b.Dispose()
End Try
'背景以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Background
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のセルで、背景を描画する時
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//選択されているか調べ、色を決定する
//bColor1が開始色、bColor2が終了色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.CellStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.CellStyle.BackColor;
bColor2 = Color.LemonChiffon;
}
//グラデーションブラシを作成
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
e.CellBounds, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//セルを塗りつぶす
e.Graphics.FillRectangle(b, e.CellBounds);
}
//背景以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Background;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
单元格背景显示图像
[VB.NET]
'セルの背景に表示する画像
Private cellBackImage As New Bitmap("C:/back.gif")
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のセルで、背景を描画する時
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'背景だけを描画する
Dim backParts As DataGridViewPaintParts = _
e.PaintParts And (DataGridViewPaintParts.Background Or _
DataGridViewPaintParts.SelectionBackground)
e.Paint(e.ClipBounds, backParts)
'画像をセルの真ん中に描画する
Dim x As Integer = e.CellBounds.X + _
(e.CellBounds.Width - cellBackImage.Width) / 2
Dim y As Integer = e.CellBounds.Y + _
(e.CellBounds.Height - cellBackImage.Height) / 2
e.Graphics.DrawImage(cellBackImage, x, y)
'背景以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not backParts
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//セルの背景に表示する画像
private Bitmap cellBackImage = new Bitmap("C://back.gif");
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のセルで、背景を描画する時
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//背景だけを描画する
DataGridViewPaintParts backParts = e.PaintParts &
(DataGridViewPaintParts.Background |
DataGridViewPaintParts.SelectionBackground);
e.Paint(e.ClipBounds, backParts);
//画像をセルの真ん中に描画する
int x = e.CellBounds.X +
(e.CellBounds.Width - cellBackImage.Width) / 2;
int y = e.CellBounds.Y +
(e.CellBounds.Height - cellBackImage.Height) / 2;
e.Graphics.DrawImage(cellBackImage, x, y);
//背景以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~backParts;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
42. DataGridView行样式描画
利用RowPostPaint事件描画
[VB.NET]
'RowPostPaintイベントハンドラ
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
'線の色を決定する
Dim linePen As Pen
Select Case e.RowIndex Mod 3
Case 0
linePen = Pens.Blue
Case 1
linePen = Pens.Green
Case Else
linePen = Pens.Red
End Select
'線を引く位置を計算する
Dim startX As Integer = IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim startY As Integer = e.RowBounds.Top + e.RowBounds.Height - 1
Dim endX As Integer = startX + _
dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - _
dgv.HorizontalScrollingOffset
'線を引く
e.Graphics.DrawLine(linePen, startX, startY, endX, startY)
End Sub
[C#]
//RowPostPaintイベントハンドラ
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//線の色を決定する
Pen linePen;
switch (e.RowIndex % 3)
{
case 0:
linePen = Pens.Blue;
break;
case 1:
linePen = Pens.Green;
break;
default:
linePen = Pens.Red;
break;
}
//線を引く位置を計算する
int startX = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int startY = e.RowBounds.Top + e.RowBounds.Height - 1;
int endX = startX + dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
dgv.HorizontalScrollingOffset;
//線を引く
e.Graphics.DrawLine(linePen,
startX, startY, endX, startY);
}
利用RowPrePaint事件描画
[VB.NET]
'RowPrePaintイベントハンドラ
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
'背景を描画するか
If (e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'選択されているか調べ、色を決定する
'bColor1が開始色、bColor2が終了色
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.InheritedRowStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.InheritedRowStyle.BackColor
bColor2 = Color.YellowGreen
End If
'グラデーションの範囲を計算する
'ヘッダーを除くセルの部分だけ描画する
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim rectLeft2 As Integer = _
IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim rectLeft As Integer = _
rectLeft2 - dgv.HorizontalScrollingOffset
Dim rectWidth As Integer = _
dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)
Dim rect As New Rectangle(rectLeft, e.RowBounds.Top, _
rectWidth, e.RowBounds.Height - 1)
'グラデーションブラシを作成
Using b As New System.Drawing.Drawing2D.LinearGradientBrush( _
rect, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
'描画する範囲を計算する
rect.X = rectLeft2
rect.Width -= dgv.HorizontalScrollingOffset
'セルを塗りつぶす
e.Graphics.FillRectangle(b, rect)
End Using
'ヘッダーを描画する
e.PaintHeader(True)
'背景を描画しないようにする
e.PaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Background
End If
End Sub
'ColumnWidthChangedイベントハンドラ
Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, _
ByVal e As DataGridViewColumnEventArgs) _
Handles DataGridView1.ColumnWidthChanged
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv.Invalidate()
End Sub
[C#]
//RowPrePaintイベントハンドラ
private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//背景を描画するか
if ((e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//選択されているか調べ、色を決定する
//bColor1が開始色、bColor2が終了色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.InheritedRowStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.InheritedRowStyle.BackColor;
bColor2 = Color.YellowGreen;
}
//グラデーションの範囲を計算する
//ヘッダーを除くセルの部分だけ描画する
DataGridView dgv = (DataGridView)sender;
int rectLeft2 = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int rectLeft = rectLeft2 - dgv.HorizontalScrollingOffset;
int rectWidth = dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible);
Rectangle rect = new Rectangle(rectLeft, e.RowBounds.Top,
rectWidth, e.RowBounds.Height - 1);
//グラデーションブラシを作成
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
rect, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//描画する範囲を計算する
rect.X = rectLeft2;
rect.Width -= dgv.HorizontalScrollingOffset;
//セルを塗りつぶす
e.Graphics.FillRectangle(b, rect);
}
//ヘッダーを描画する
e.PaintHeader(true);
//背景を描画しないようにする
e.PaintParts &= ~DataGridViewPaintParts.Background;
}
}
//ColumnWidthChangedイベントハンドラ
private void DataGridView1_ColumnWidthChanged(object sender,
DataGridViewColumnEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
dgv.Invalidate();
}
43. DataGridView显示行号
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'列ヘッダーかどうか調べる
If e.ColumnIndex < 0 And e.RowIndex >= 0 Then
'セルを描画する
e.Paint(e.ClipBounds, DataGridViewPaintParts.All)
'行番号を描画する範囲を決定する
'e.AdvancedBorderStyleやe.CellStyle.Paddingは無視しています
Dim indexRect As Rectangle = e.CellBounds
indexRect.Inflate(-2, -2)
'行番号を描画する
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.CellStyle.Font, _
indexRect, _
e.CellStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//列ヘッダーかどうか調べる
if (e.ColumnIndex < 0 && e.RowIndex >= 0)
{
//セルを描画する
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
//行番号を描画する範囲を決定する
//e.AdvancedBorderStyleやe.CellStyle.Paddingは無視しています
Rectangle indexRect = e.CellBounds;
indexRect.Inflate(-2, -2);
//行番号を描画する
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.CellStyle.Font,
indexRect,
e.CellStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
//描画が完了したことを知らせる
e.Handled = true;
}
}
利用RowPostPaint事件描画
[VB.NET]
'RowPostPaintイベントハンドラ
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.RowHeadersVisible Then
'行番号を描画する範囲を決定する
Dim rect As New Rectangle(e.RowBounds.Left, e.RowBounds.Top, _
dgv.RowHeadersWidth, e.RowBounds.Height)
rect.Inflate(-2, -2)
'行番号を描画する
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.InheritedRowStyle.Font, _
rect, _
e.InheritedRowStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
End If
End Sub
[C#]
//RowPostPaintイベントハンドラ
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.RowHeadersVisible)
{
//行番号を描画する範囲を決定する
Rectangle rect = new Rectangle(
e.RowBounds.Left, e.RowBounds.Top,
dgv.RowHeadersWidth, e.RowBounds.Height);
rect.Inflate(-2, -2);
//行番号を描画する
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
rect,
e.InheritedRowStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
}
}
44. DataGridView焦点所在单元格焦点框不显示的设定
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のとき
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
'フォーカス枠以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Focus
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のとき
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
//フォーカス枠以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Focus;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
利用RowPrePaint事件实现
[VB.NET]
'RowPrePaintイベントハンドラ
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
'フォーカス枠を描画しない
e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus
End Sub
[C#]
//RowPrePaintイベントハンドラ
private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//フォーカス枠を描画しない
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第四部分。
19. DataGridView中的ContextMenuStrip属性
20. DataGridView指定滚动框位置
21. DataGridView手动追加列
22. DataGridView全体分界线样式设置
23. DataGridView根据单元格属性更改显示内容
24. DataGridView新追加行的行高样式设置る
25. DataGridView新追加行单元格默认值设置
19. DataGridView中的ContextMenuStrip属性
[VB.NET]
'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
[C#]
//DataGridViewのContextMenuStripを設定する
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
//列のContextMenuStripを設定する
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
//列ヘッダーのContextMenuStripを設定する
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
//行のContextMenuStripを設定する
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
//セルのContextMenuStripを設定する
DataGridView1[0, 1].ContextMenuStrip = this.ContextMenuStrip4;
也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义
[VB.NET]
'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
[C#]
//CellContextMenuStripNeededイベントハンドラ
private void DataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
//列ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
//行ヘッダーに表示するContextMenuStripを設定する
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
//セルが整数型のときに表示するContextMenuStripを変更する
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
20. DataGridView指定滚动框位置
[VB.NET]
'先頭の行までスクロールする
DataGridView1.FirstDisplayedScrollingRowIndex = 0
'先頭の列までスクロールする
DataGridView1.FirstDisplayedScrollingColumnIndex = 0
[C#]
//先頭の行までスクロールする
DataGridView1.FirstDisplayedScrollingRowIndex = 0;
//先頭の列までスクロールする
DataGridView1.FirstDisplayedScrollingColumnIndex = 0;
21. DataGridView手动追加列
[VB.NET]
'列が自動的に作成されないようにする
DataGridView1.AutoGenerateColumns = False
'データソースを設定する
DataGridView1.DataSource = BindingSource1
'DataGridViewTextBoxColumn列を作成する
Dim textColumn As New DataGridViewTextBoxColumn()
'データソースの"Column1"をバインドする
textColumn.DataPropertyName = "Column1"
'名前とヘッダーを設定する
textColumn.Name = "Column1"
textColumn.HeaderText = "Column1"
'列を追加する
DataGridView1.Columns.Add(textColumn)
[C#]
//列が自動的に作成されないようにする
DataGridView1.AutoGenerateColumns = false;
//データソースを設定する
DataGridView1.DataSource = BindingSource1;
//DataGridViewTextBoxColumn列を作成する
DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
//データソースの"Column1"をバインドする
textColumn.DataPropertyName = "Column1";
//名前とヘッダーを設定する
textColumn.Name = "Column1";
textColumn.HeaderText = "Column1";
//列を追加する
DataGridView1.Columns.Add(textColumn);
22. DataGridView全体分界线样式设置
[VB.NET]
'DataGridViewの境界線を3Dにする
DataGridView1.BorderStyle = BorderStyle.Fixed3D
[C#]
//DataGridViewの境界線を3Dにする
DataGridView1.BorderStyle = BorderStyle.Fixed3D;
单元格上下左右分界线样式设置
[VB.NET]
'セルの上と左を二重線のくぼんだ境界線にし、
'下と右を一重線のくぼんだ境界線にする
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble
[C#]
//セルの上と左を二重線のくぼんだ境界線にし、
//下と右を一重線のくぼんだ境界線にする
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble;
23. DataGridView根据单元格属性更改显示内容
如下例,当该列是字符串时,自动转换文字大小写
[VB.NET]
'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
[C#]
//CellFormattingイベントハンドラ
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//セルの列を確認
if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)
{
//大文字にして表示する
string str = e.Value.ToString();
e.Value = str.ToUpper();
//フォーマットの必要がないことを知らせる
e.FormattingApplied = true;
}
}
24. DataGridView新追加行的行高样式设置
行高设置
[VB.NET]
'行テンプレートの高さを設定する
DataGridView1.RowTemplate.Height = 50
'行の最低の高さを設定する
DataGridView1.RowTemplate.MinimumHeight = 50
[C#]
//行テンプレートの高さを設定する
DataGridView1.RowTemplate.Height = 50;
//行の最低の高さを設定する
DataGridView1.RowTemplate.MinimumHeight = 50;
样式设置
[VB.NET]
'行テンプレートのセルスタイルの背景色を黄色にする
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow
[C#]
//行テンプレートのセルスタイルの背景色を黄色にする
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow;
25. DataGridView新追加行单元格默认值设置
[VB.NET]
'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
[C#]
//DefaultValuesNeededイベントハンドラ
private void DataGridView1_DefaultValuesNeeded(object sender,
DataGridViewRowEventArgs e)
{
//セルの既定値を指定する
e.Row.Cells["Column1"].Value = 0;
e.Row.Cells["Column2"].Value = "-";
}
DataGridView控件用法合集(六)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第六部分。
DataGridView排序
29. DataGridView行排序(点击列表头自动排序的设置)
30. DataGridView自动行排序(新追加值也会自动排序)
31. DataGridView自动行排序禁止情况下的排序
32. DataGridView指定列指定排序
29. DataGridView行排序(点击列表头自动排序的设置)
[VB.NET]
'並び替えができないようにする
For Each c As DataGridViewColumn In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.NotSortable
Next c
[C#]
//並び替えができないようにする
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.NotSortable;
30. DataGridView自动行排序(新追加值也会自动排序)
[VB.NET]
'フォームの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 System.ComponentModel.ListSortDirection = _
System.ComponentModel.ListSortDirection.Ascending
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
DataGridView1.SortedColumn.Equals(sortColumn) Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Ascending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
'並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection)
End Sub
[C#]
//フォームのLoadイベントハンドラ
private void Form1_Load(object sender, EventArgs e)
{
//自動的に並び替えられるようにする
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.Automatic;
}
//Button1のClickイベントハンドラ
private void Button1_Click(object sender, EventArgs e)
{
if (DataGridView1.CurrentCell == null)
return;
//並び替える列を決める
DataGridViewColumn sortColumn = DataGridView1.CurrentCell.OwningColumn;
//並び替えの方向(昇順か降順か)を決める
ListSortDirection sortDirection = ListSortDirection.Ascending;
if (DataGridView1.SortedColumn != null &&
DataGridView1.SortedColumn.Equals(sortColumn))
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Ascending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
//並び替えを行う
DataGridView1.Sort(sortColumn, sortDirection);
}
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
Me.SortRows(DataGridView1.SortedColumn, False)
End If
End Sub
''' <summary>
''' 指定された列を基準にして並び替えを行う
''' </summary>
''' <param name="sortColumn">基準にする列</param>
''' <param name="orderToggle">並び替えの方向をトグルで変更する</param>
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 System.ComponentModel.ListSortDirection
If orderToggle Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Ascending, _
System.ComponentModel.ListSortDirection.Descending)
Else
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
Dim sOrder As SortOrder = _
IIf(sortDirection = System.ComponentModel.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 += new DataGridViewCellMouseEventHandler(
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);
}
/// <summary>
/// 指定された列を基準にして並び替えを行う
/// </summary>
/// <param name="sortColumn">基準にする列</param>
/// <param name="orderToggle">並び替えの方向をトグルで変更する</param>
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;
}
else
{
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指定列指定排序
[VB.NET]
'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控件用法合集(七)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第七部分。
DataGridView样式
33. DataGridView单元格样式设置
34. DataGridView文字表示位置的设定
35. DataGridView单元格内文字列换行
36. DataGridView单元格DBNull值表示的设定
37. DataGridView单元格样式格式化
38. DataGridView指定单元格颜色设定
39. DataGridView单元格文字字体设置
40. DataGridView根据单元格值设定单元格样式
33. DataGridView单元格样式设置
指定行列的样式设定
[VB.NET]
'インデックス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;
奇数行样式设定
[VB.NET]
'奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow
[C#]
//奇数行のセルの背景色を黄緑色にする
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;
行,列表头部的样式设定
[VB.NET]
'列ヘッダーの背景色をアイボリーにする
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
下例说明
[VB.NET]
'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行目のセルスタイル
'"[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行目のセルスタイル
//"[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);
复数行列的样式设定
[VB.NET]
'奇数列の背景色を変更する
'効率的な方法
Dim cellStyle As New DataGridViewCellStyle()
cellStyle.BackColor = Color.Yellow
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle = cellStyle
End If
Next i
'非効率的な方法
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle.BackColor = Color.Yellow
End If
Next i
[C#]
//奇数列の背景色を変更する
//効率的な方法
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.BackColor = Color.Yellow;
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle = cellStyle;
}
//非効率的な方法
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle.BackColor = Color.Yellow;
}
34. DataGridView文字表示位置的设定
单元格的设定
[VB.NET]
'"Column1"列のセルのテキストの配置を上下左右とも中央にする
DataGridView1.Columns("Column1").DefaultCellStyle.Alignment = _
DataGridViewContentAlignment.MiddleCenter
[C#]
//"Column1"列のセルのテキストの配置を上下左右とも中央にする
DataGridView1.Columns["Column1"].DefaultCellStyle.Alignment =
DataGridViewContentAlignment.MiddleCenter;
表头的设定
[VB.NET]
'"Column1"列のヘッダーのテキストの配置を上下左右とも中央にする
DataGridView1.Columns("Column1").HeaderCell.Style.Alignment = _
DataGridViewContentAlignment.MiddleCenter
[C#]
//"Column1"列のヘッダーのテキストの配置を上下左右とも中央にする
DataGridView1.Columns["Column1"].HeaderCell.Style.Alignment =
DataGridViewContentAlignment.MiddleCenter;
35. DataGridView单元格内文字列换行
[VB.NET]
'"Column1"列のセルのテキストを折り返して表示する
DataGridView1.Columns("Column1").DefaultCellStyle.WrapMode = _
DataGridViewTriState.True
'ヘッダーも折り返して表示するなら、次のようにする
DataGridView1.Columns("Column1").HeaderCell.Style.WrapMode = _
DataGridViewTriState.True
[C#]
//"Column1"列のセルのテキストを折り返して表示する
DataGridView1.Columns["Column1"].DefaultCellStyle.WrapMode =
DataGridViewTriState.True;
//ヘッダーも折り返して表示するなら、次のようにする
DataGridView1.Columns["Column1"].HeaderCell.Style.WrapMode =
DataGridViewTriState.True;
36. DataGridView单元格DBNull值表示的设定
[VB.NET]
DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)"
[C#]
DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)";
单元格内NullValue属性设定的值输入,表示单元格内为Null值
[VB.NET]
DataGridView1.DefaultCellStyle.NullValue = "-"
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X"
[C#]
DataGridView1.DefaultCellStyle.NullValue = "-";
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X";
37. DataGridView单元格样式格式化
[VB.NET]
'列のセルのテキストの書式を地域通貨として指定する
DataGridView1.Columns(0).DefaultCellStyle.Format = "c"
DataGridView1.Columns(1).DefaultCellStyle.Format = "c"
'2列目のカルチャを変更する
DataGridView1.Columns(1).DefaultCellStyle.FormatProvider = _
New System.Globalization.CultureInfo("en-US")
[C#]
//列のセルのテキストの書式を地域通貨として指定する
DataGridView1.Columns[0].DefaultCellStyle.Format = "c";
DataGridView1.Columns[1].DefaultCellStyle.Format = "c";
//2列目のカルチャを変更する
DataGridView1.Columns[1].DefaultCellStyle.FormatProvider =
new System.Globalization.CultureInfo("en-US");
Format的参数一览(整数)
書式
説明
値が"123456"の時
書式なし
123456
C
通貨
/123,456
D
10進数
123456
E
指数
1.234560E+005
F
固定小数点
123456.00
G
一般
123456
N
数値
123,456.00
P
パーセント
12,345,600.00%
R
ラウンドトリップ
(エラーが出る)
X
16進数
1E240
0
123456
00000000
00123456
########
123456
#,##0
123,456
%0
%12345600
00.000E0
12.346E4
プラス#;マイナス#;ゼロ
プラス123456
iの値は「#」です。
iの値は「123456」です
Format的参数一览(小数)
書式
説明
値が"1.23456789"の時
書式なし
1.23456789
C
通貨
/1
D
10進数
(エラーが出る)
E
指数
1.234568E+000
F
固定小数点
1.23
G
一般
1.23456789
N
数値
1.23
P
パーセント
123.46%
R
ラウンドトリップ
1.23456789
X
16進数
(エラーが出る)
00.0000000000
01.2345678900
##.##########
1.23456789
#,##0.000
1.235
%0.##
%123.46
00.000E0
12.346E-1
プラス#;マイナス#;ゼロ
プラス1.23
dの値は「#.##」です。
dの値は「1.23」です。
38. DataGridView指定单元格颜色设定
光标下的单元格颜色自动变换
[VB.NET]
'DataGridView1のCellMouseEnterイベントハンドラ
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを変更する
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Red
End If
End Sub
'DataGridView1のCellMouseLeaveイベントハンドラ
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを元に戻す
'セルスタイルを削除するなら、nullを設定してもよい
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Empty
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Empty
End If
End Sub
[C#]
//DataGridView1のCellMouseEnterイベントハンドラ
private void DataGridView1_CellMouseEnter(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを変更する
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
}
}
//DataGridView1のCellMouseLeaveイベントハンドラ
private void DataGridView1_CellMouseLeave(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを元に戻す
//セルスタイルを削除するなら、nullを設定してもよい
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Empty;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Empty;
}
}
表头部单元格颜色设定
[VB.NET]
'列ヘッダーの背景色を黄色にする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow
'行ヘッダーの背景色を黄緑色にする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen
'左上隅のヘッダーセルの背景色を青にする
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue
[C#]
//列ヘッダーの背景色を黄色にする
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;
//行ヘッダーの背景色を黄緑色にする
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen;
//左上隅のヘッダーセルの背景色を青にする
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue;
39. DataGridView单元格文字字体设置
光标下单元格字体设置为粗体
[VB.NET]
'デフォルトのセルスタイル
Private defaultCellStyle As DataGridViewCellStyle
'マウスポインタの下にあるセルのセルスタイル
Private mouseCellStyle As DataGridViewCellStyle
'フォームのLoadイベントハンドラ
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'デフォルトのセルスタイルの設定
Me.defaultCellStyle = New DataGridViewCellStyle()
'現在のセルのセルスタイルの設定
Me.mouseCellStyle = New DataGridViewCellStyle()
Me.mouseCellStyle.Font = New Font(DataGridView1.Font, _
DataGridView1.Font.Style Or FontStyle.Bold)
End Sub
'DataGridView1のCellMouseEnterイベントハンドラ
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを変更する
dgv(e.ColumnIndex, e.RowIndex).Style = Me.mouseCellStyle
End If
End Sub
'DataGridView1のCellMouseLeaveイベントハンドラ
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
'ヘッダー以外のセル
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
'セルスタイルを元に戻す
'セルスタイルを削除するなら、nullを設定してもよい
dgv(e.ColumnIndex, e.RowIndex).Style = Me.defaultCellStyle
End If
End Sub
[C#]
//デフォルトのセルスタイル
private DataGridViewCellStyle defaultCellStyle;
//マウスポインタの下にあるセルのセルスタイル
private DataGridViewCellStyle mouseCellStyle;
//フォームのLoadイベントハンドラ
private void Form1_Load(object sender, EventArgs e)
{
//デフォルトのセルスタイルの設定
this.defaultCellStyle = new DataGridViewCellStyle();
//現在のセルのセルスタイルの設定
this.mouseCellStyle = new DataGridViewCellStyle();
this.mouseCellStyle.Font = new Font(DataGridView1.Font,
DataGridView1.Font.Style | FontStyle.Bold);
}
//DataGridView1のCellEnterイベントハンドラ
private void DataGridView1_CellEnter(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを変更する
dgv[e.ColumnIndex, e.RowIndex].Style = this.mouseCellStyle;
}
}
//DataGridView1のCellLeaveイベントハンドラ
private void DataGridView1_CellLeave(object sender,
DataGridViewCellEventArgs e)
{
//ヘッダー以外のセル
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//セルスタイルを元に戻す
//セルスタイルを削除するなら、nullを設定してもよい
dgv[e.ColumnIndex, e.RowIndex].Style = this.defaultCellStyle;
}
}
40. DataGridView根据单元格值设定单元格样式
单元格负数情况下显示黄色,0的情况下显示红色
[VB.NET]
'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 Integer Then
Dim val As Integer = CInt(e.Value)
'セルの値により、背景色を変更する
If val < 0 Then
e.CellStyle.BackColor = Color.Yellow
Else If val = 0 Then
e.CellStyle.BackColor = Color.Red
End If
End If
End Sub
[C#]
//CellFormattingイベントハンドラ
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//セルの列を確認
if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is int)
{
int val = (int)e.Value;
//セルの値により、背景色を変更する
if (val < 0)
{
e.CellStyle.BackColor = Color.Yellow;
}
else if (val == 0)
{
e.CellStyle.BackColor = Color.Red;
}
}
}
DataGridView控件用法合集(八)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第八部分。
DataGridView Owner描画
41. DataGridView设置单元格背景颜色
42. DataGridView行样式描画
43. DataGridView显示行号
44. DataGridView焦点所在单元格焦点框不显示的设定
41. DataGridView设置单元格背景颜色
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のセルで、背景を描画する時
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'選択されているか調べ、色を決定する
'bColor1が開始色、bColor2が終了色
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.CellStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.CellStyle.BackColor
bColor2 = Color.LemonChiffon
End If
'グラデーションブラシを作成
Dim b As New System.Drawing.Drawing2D.LinearGradientBrush( _
e.CellBounds, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
Try
'セルを塗りつぶす
e.Graphics.FillRectangle(b, e.CellBounds)
Finally
b.Dispose()
End Try
'背景以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Background
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のセルで、背景を描画する時
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//選択されているか調べ、色を決定する
//bColor1が開始色、bColor2が終了色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.CellStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.CellStyle.BackColor;
bColor2 = Color.LemonChiffon;
}
//グラデーションブラシを作成
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
e.CellBounds, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//セルを塗りつぶす
e.Graphics.FillRectangle(b, e.CellBounds);
}
//背景以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Background;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
单元格背景显示图像
[VB.NET]
'セルの背景に表示する画像
Private cellBackImage As New Bitmap("C:/back.gif")
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のセルで、背景を描画する時
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'背景だけを描画する
Dim backParts As DataGridViewPaintParts = _
e.PaintParts And (DataGridViewPaintParts.Background Or _
DataGridViewPaintParts.SelectionBackground)
e.Paint(e.ClipBounds, backParts)
'画像をセルの真ん中に描画する
Dim x As Integer = e.CellBounds.X + _
(e.CellBounds.Width - cellBackImage.Width) / 2
Dim y As Integer = e.CellBounds.Y + _
(e.CellBounds.Height - cellBackImage.Height) / 2
e.Graphics.DrawImage(cellBackImage, x, y)
'背景以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not backParts
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//セルの背景に表示する画像
private Bitmap cellBackImage = new Bitmap("C://back.gif");
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のセルで、背景を描画する時
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//背景だけを描画する
DataGridViewPaintParts backParts = e.PaintParts &
(DataGridViewPaintParts.Background |
DataGridViewPaintParts.SelectionBackground);
e.Paint(e.ClipBounds, backParts);
//画像をセルの真ん中に描画する
int x = e.CellBounds.X +
(e.CellBounds.Width - cellBackImage.Width) / 2;
int y = e.CellBounds.Y +
(e.CellBounds.Height - cellBackImage.Height) / 2;
e.Graphics.DrawImage(cellBackImage, x, y);
//背景以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~backParts;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
42. DataGridView行样式描画
利用RowPostPaint事件描画
[VB.NET]
'RowPostPaintイベントハンドラ
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
'線の色を決定する
Dim linePen As Pen
Select Case e.RowIndex Mod 3
Case 0
linePen = Pens.Blue
Case 1
linePen = Pens.Green
Case Else
linePen = Pens.Red
End Select
'線を引く位置を計算する
Dim startX As Integer = IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim startY As Integer = e.RowBounds.Top + e.RowBounds.Height - 1
Dim endX As Integer = startX + _
dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - _
dgv.HorizontalScrollingOffset
'線を引く
e.Graphics.DrawLine(linePen, startX, startY, endX, startY)
End Sub
[C#]
//RowPostPaintイベントハンドラ
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//線の色を決定する
Pen linePen;
switch (e.RowIndex % 3)
{
case 0:
linePen = Pens.Blue;
break;
case 1:
linePen = Pens.Green;
break;
default:
linePen = Pens.Red;
break;
}
//線を引く位置を計算する
int startX = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int startY = e.RowBounds.Top + e.RowBounds.Height - 1;
int endX = startX + dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
dgv.HorizontalScrollingOffset;
//線を引く
e.Graphics.DrawLine(linePen,
startX, startY, endX, startY);
}
利用RowPrePaint事件描画
[VB.NET]
'RowPrePaintイベントハンドラ
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
'背景を描画するか
If (e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
'選択されているか調べ、色を決定する
'bColor1が開始色、bColor2が終了色
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.InheritedRowStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.InheritedRowStyle.BackColor
bColor2 = Color.YellowGreen
End If
'グラデーションの範囲を計算する
'ヘッダーを除くセルの部分だけ描画する
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim rectLeft2 As Integer = _
IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim rectLeft As Integer = _
rectLeft2 - dgv.HorizontalScrollingOffset
Dim rectWidth As Integer = _
dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)
Dim rect As New Rectangle(rectLeft, e.RowBounds.Top, _
rectWidth, e.RowBounds.Height - 1)
'グラデーションブラシを作成
Using b As New System.Drawing.Drawing2D.LinearGradientBrush( _
rect, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
'描画する範囲を計算する
rect.X = rectLeft2
rect.Width -= dgv.HorizontalScrollingOffset
'セルを塗りつぶす
e.Graphics.FillRectangle(b, rect)
End Using
'ヘッダーを描画する
e.PaintHeader(True)
'背景を描画しないようにする
e.PaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Background
End If
End Sub
'ColumnWidthChangedイベントハンドラ
Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, _
ByVal e As DataGridViewColumnEventArgs) _
Handles DataGridView1.ColumnWidthChanged
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv.Invalidate()
End Sub
[C#]
//RowPrePaintイベントハンドラ
private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//背景を描画するか
if ((e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//選択されているか調べ、色を決定する
//bColor1が開始色、bColor2が終了色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.InheritedRowStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.InheritedRowStyle.BackColor;
bColor2 = Color.YellowGreen;
}
//グラデーションの範囲を計算する
//ヘッダーを除くセルの部分だけ描画する
DataGridView dgv = (DataGridView)sender;
int rectLeft2 = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int rectLeft = rectLeft2 - dgv.HorizontalScrollingOffset;
int rectWidth = dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible);
Rectangle rect = new Rectangle(rectLeft, e.RowBounds.Top,
rectWidth, e.RowBounds.Height - 1);
//グラデーションブラシを作成
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
rect, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//描画する範囲を計算する
rect.X = rectLeft2;
rect.Width -= dgv.HorizontalScrollingOffset;
//セルを塗りつぶす
e.Graphics.FillRectangle(b, rect);
}
//ヘッダーを描画する
e.PaintHeader(true);
//背景を描画しないようにする
e.PaintParts &= ~DataGridViewPaintParts.Background;
}
}
//ColumnWidthChangedイベントハンドラ
private void DataGridView1_ColumnWidthChanged(object sender,
DataGridViewColumnEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
dgv.Invalidate();
}
43. DataGridView显示行号
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'列ヘッダーかどうか調べる
If e.ColumnIndex < 0 And e.RowIndex >= 0 Then
'セルを描画する
e.Paint(e.ClipBounds, DataGridViewPaintParts.All)
'行番号を描画する範囲を決定する
'e.AdvancedBorderStyleやe.CellStyle.Paddingは無視しています
Dim indexRect As Rectangle = e.CellBounds
indexRect.Inflate(-2, -2)
'行番号を描画する
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.CellStyle.Font, _
indexRect, _
e.CellStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//列ヘッダーかどうか調べる
if (e.ColumnIndex < 0 && e.RowIndex >= 0)
{
//セルを描画する
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
//行番号を描画する範囲を決定する
//e.AdvancedBorderStyleやe.CellStyle.Paddingは無視しています
Rectangle indexRect = e.CellBounds;
indexRect.Inflate(-2, -2);
//行番号を描画する
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.CellStyle.Font,
indexRect,
e.CellStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
//描画が完了したことを知らせる
e.Handled = true;
}
}
利用RowPostPaint事件描画
[VB.NET]
'RowPostPaintイベントハンドラ
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.RowHeadersVisible Then
'行番号を描画する範囲を決定する
Dim rect As New Rectangle(e.RowBounds.Left, e.RowBounds.Top, _
dgv.RowHeadersWidth, e.RowBounds.Height)
rect.Inflate(-2, -2)
'行番号を描画する
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.InheritedRowStyle.Font, _
rect, _
e.InheritedRowStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
End If
End Sub
[C#]
//RowPostPaintイベントハンドラ
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.RowHeadersVisible)
{
//行番号を描画する範囲を決定する
Rectangle rect = new Rectangle(
e.RowBounds.Left, e.RowBounds.Top,
dgv.RowHeadersWidth, e.RowBounds.Height);
rect.Inflate(-2, -2);
//行番号を描画する
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
rect,
e.InheritedRowStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
}
}
44. DataGridView焦点所在单元格焦点框不显示的设定
[VB.NET]
'CellPaintingイベントハンドラ
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
'ヘッダー以外のとき
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
'フォーカス枠以外が描画されるようにする
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Focus
'セルを描画する
e.Paint(e.ClipBounds, paintParts)
'描画が完了したことを知らせる
e.Handled = True
End If
End Sub
[C#]
//CellPaintingイベントハンドラ
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//ヘッダー以外のとき
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
//フォーカス枠以外が描画されるようにする
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Focus;
//セルを描画する
e.Paint(e.ClipBounds, paintParts);
//描画が完了したことを知らせる
e.Handled = true;
}
}
利用RowPrePaint事件实现
[VB.NET]
'RowPrePaintイベントハンドラ
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
'フォーカス枠を描画しない
e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus
End Sub
[C#]
//RowPrePaintイベントハンドラ
private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//フォーカス枠を描画しない
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}