【概要】
様々な状況において、マウスの位置をもとに行や列、セルなどの情報を取得する必要があります。グリッド上の特定の位置に該当するUIElementを取得するためには、UIElement.ElementFromPointメソッドを使用します。
【該当するコンポーネント】
UltraWinGrid
【該当するバージョン】
全てのバージョン
【記事の種類】
FAQ
【詳細】
(質問)ユーザーがクリックした行や列、セルを正確に判別するためには?
(回答)まずグリッドのDisplayLayout.UIElementオブジェクトのElementFromPointメソッドを使用して、マウスのX/Y座標に相当するグリッド表面上のUIElementを取得します。 次に、UIElementに関連づけられた行(UltraGridRow)やセル(UltraGridCell)といった情報を取得するために、GetContextメソッドを使用します。 以下がそのコード例です。なお、マウスクリックイベントをハンドルするためには、MouseClick,MouseUp,MouseDownイベントなどを用います。
(C#)
private void ultraGrid1_MouseClick(object sender, MouseEventArgs e)
{
UltraGrid grid = sender as UltraGrid;
//マウス位置からエレメントを取得
UIElement element = grid.DisplayLayout.UIElement.ElementFromPoint(e.Location);
//または、LastElementEnteredを利用することも可能
//UIElement el = grid.DisplayLayout.UIElement.LastElementEntered;
StringBuilder sb = new StringBuilder();
UltraGridRow row = element.GetContext(typeof(UltraGridRow)) as UltraGridRow;
if (row != null)
{
//UltraGridRowを取得
sb.AppendFormat("Row Index:{0}", row.Index);
sb.AppendLine();
}
UltraGridColumn column = element.GetContext(typeof(UltraGridColumn)) as UltraGridColumn;
if (column != null)
{
//UltraGridColumnを取得
sb.AppendFormat("Column Index:{0}", column.Index);
sb.AppendLine();
}
UltraGridCell cell = element.GetContext(typeof(UltraGridCell)) as UltraGridCell;
if (cell != null)
{
//UltraGridCellを取得
sb.AppendFormat("Cell Value:{0}", cell.Value);
sb.AppendLine();
}
Infragistics.Win.UltraWinGrid.ColumnHeader colHeader = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader)) as Infragistics.Win.UltraWinGrid.ColumnHeader;
if (colHeader != null)
{
//ColumnHeaderを取得
sb.AppendFormat("Column Header Caption:{0}", colHeader.Caption);
sb.AppendLine();
}
if (sb.Length > 0)
{
MessageBox.Show(sb.ToString());
}
}
(VB)
Private Sub UltraGrid1_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
Dim grid As UltraGrid = sender
'マウス位置からエレメントを取得
Dim element As UIElement = grid.DisplayLayout.UIElement.ElementFromPoint(e.Location)
'または、LastElementEnteredを利用することも可能
'elemnt = grid.DisplayLayout.UIElement.LastElementEntered
Dim sb As New StringBuilder
Dim row As UltraGridRow = element.GetContext(GetType(UltraGridRow))
If Not row Is Nothing Then
sb.AppendFormat("Row Index:{0}", row.Index)
sb.AppendLine()
End If
Dim column As UltraGridColumn = element.GetContext(GetType(UltraGridColumn))
If Not column Is Nothing Then
sb.AppendFormat("Column Index:{0}", column.Index)
sb.AppendLine()
End If
Dim cell As UltraGridCell = element.GetContext(GetType(UltraGridCell))
If Not cell Is Nothing Then
sb.AppendFormat("Cell Value:{0}", cell.Value)
sb.AppendLine()
End If
Dim colHeader As Infragistics.Win.UltraWinGrid.ColumnHeader = element.GetContext(GetType(Infragistics.Win.UltraWinGrid.ColumnHeader))
If Not colHeader Is Nothing Then
sb.AppendFormat("Column Header Caption:{0}", colHeader.Caption)
sb.AppendLine()
End If
If (sb.Length > 0) Then
MessageBox.Show(sb.ToString())
End If
End Sub