プログラムから DataGrid の CurrentCell を設定し、セルを選択するには DataGridCellInfo オブジェクトを生成(new)して代入します。
セルを選択した状態

DataGridのセルをコードから選択する方法
行インデックス・列インデックスから DataGridCellInfo オブジェクト を生成し、データグリッドの CurrentCell プロパティに代入します。using System.Windows.Controls;
int rowIndex = 選択したい行番号; // 0 ~
int columnIndex = 選択したい列番号; // 0 ~
// データグリッドにフォーカスが必要
dataGrid.Focus();
// DataGridCellInfo を生成
DataGridCellInfo cellInfo = new DataGridCellInfo(dataGrid.Items[rowIndex], dataGrid.Columns[columnIndex]);
// CurrentCell を設定
dataGrid.CurrentCell = cellInfo;
// 選択中の行を設定
dataGrid.SelectedIndex = rowIndex;
- 1行目: 後述する DataGridCellInfo の生成に必要です。
- 3行目: 選択したい行 の インデックス を代入します。
- 4行目: 選択したい列 の インデックス を代入します。
- 7行目: データグリッドにフォーカスが無いと選択されません。
- 10行目: 行インデックス・列インデックスから、DataGridCellInfo を生成します。
- 13行目: データグリッドの CurrentCell プロパティに、生成した DataGridCellInfo を代入するとセルが選択されます。
- 16行目: 選択中のセル と 選択中の行 を同じにしたい場合、 データグリッドの SelectedIndex プロパティ も変更します。
サンプルコード
XXXXX.xaml.cs画面には次のコントロールが配置されています。
- txtRowNo: 行番号入力用のテキストボックス
- txtColumnNo: 列番号入力用のテキストボックス
- dataGrid: 対象のデータグリッド
- button: 次のサンプルコードはボタンのクリックイベント
using System.Windows.Controls;
/// <summary>
/// 選択ボタンのクリックイベント
/// </summary>
private void Button_Click(object sender, RoutedEventArgs e)
{
int rowIndex = 0;
int columnIndex = 0;
if (!int.TryParse(this.txtRowNo.Text, out rowIndex))
{
MessageBox.Show("行番号を数値に変換できません。");
return;
}
if (!int.TryParse(this.txtColumnNo.Text, out columnIndex))
{
MessageBox.Show("列番号を数値に変換できません。");
return;
}
if (rowIndex < 0 || rowIndex >= dataGrid.Items.Count)
{
MessageBox.Show("行番号が範囲外です。");
return;
}
if (columnIndex < 0 || columnIndex >= dataGrid.Columns.Count)
{
MessageBox.Show("列番号が範囲外です。");
return;
}
// データグリッドにフォーカスが必要
this.dataGrid.Focus();
// DataGridCellInfo を生成
DataGridCellInfo cellInfo = new DataGridCellInfo(this.dataGrid.Items[rowIndex], this.dataGrid.Columns[columnIndex]);
// CurrentCell を設定
this.dataGrid.CurrentCell = cellInfo;
// 選択中の行を設定
this.dataGrid.SelectedIndex = rowIndex;
}
検証環境
- .NET 5.0
- Microsoft Visual Studio Professional 2019 Version 16.9.4
- Microsoft Windows 10 Pro Version 20H2 OS Build 19042.928 Experience: Windows Feature Experience Pack 120.2212.551.0