【C#】【Form】DataGridView に右クリックを適用する

■ 追加した主なコントロール

ContextMenuStrip

 * プロパティ名「contextMenuStrip1」

DataGridView

 * プロパティ名「dataGridView1」
 * ContextMenuStrip:contextMenuStrip1
 * SelectionMode:FullRowSelect(複セルを選択した場合、行全体を選択状態にする)
 * MultiSelect:false(複数行選択できないようにする)
* DataGridView のプロパティについては、以下を参照のこと
http://blogs.yahoo.co.jp/dk521123/14718079.html

■ サンプル

 * DataGridView x 1
 * ContextMenuStrip x 1

Form

private void Form1_Load(object sender, EventArgs e)
{
    var people = new List<Person>()
    {
        new Person() {Id = "001", Name = "Mike", Age = 22, },
        new Person() {Id = "002", Name = "Sam", Age = 18, },
        new Person() {Id = "xxx", Name = "Tom", Age = 32, },
    };
    this.dataGridView1.DataSource = people;
}

// [動作]のところにある。
// セルのショートカット メニューが必要な場合に発生。
private void dataGridView1_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
    {
        return;
    }

    // 選択を一旦全てクリア
    this.dataGridView1.ClearSelection();
    // で、改めて行選択
    var row = this.dataGridView1.Rows[e.RowIndex];
    row.Selected = true;
}

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    var selectedRow = this.dataGridView1.SelectedRows[0];
    var selectedPerson = selectedRow.DataBoundItem as Person;
    if (selectedPerson != null)
    {
        MessageBox.Show(
            selectedPerson.Id + " / " +
            selectedPerson.Name + " / " + 
            selectedPerson.Age);
    }
}

DataGridViewに使うクラス

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

関連記事

DataGridView ~ プロパティ編 ~

http://blogs.yahoo.co.jp/dk521123/14718079.html

DataGridView ~イベント編 ~

http://blogs.yahoo.co.jp/dk521123/23687833.html

ContextMenuStrip ~右クリックを使うには~

http://blogs.yahoo.co.jp/dk521123/22454285.html