設定
//セルをクリックしただけで、入力カーソルを有効にする
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
//複数選択不可
dataGridView1.MultiSelect = false;
//セル選択ではなく、行全体選択
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//一部の列を編集不可にする
dataGridView1.Columns[1].ReadOnly = true;
//ヘッダ列をクリックした際の並び替え禁止
foreach (DataGridViewColumn c in dataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.NotSortable;
//ボタンの背景色が白くなってしまうのを防ぐ
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.BackColor = SystemColors.Control; //ボタンの標準色を設定
Column3.DefaultCellStyle = cellStyle;
値取得
//選択された行のセル値取得
if (dataGridView1.SelectedCells.Count > 0)
{
int columnIndex = dataGridView1.SelectedCells[0].ColumnIndex; //選択列
int rowIndex = dataGridView1.SelectedCells[0].RowIndex; //選択行
string cellValue = "";
if (dataGridView1[columnIndex, rowIndex].Value != null)
{
cellValue = dataGridView1[columnIndex, rowIndex].Value.ToString(); //該当セルの値
}
}
セルを抜けなくてもCellValueChangedイベントを発生させる
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
//確定させる→セルを抜けなくてもCellValueChangedイベントが発生する
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}