2012-12-10 39 views
1

這是我在C#中的DataGrid的代碼。在一個單元上右擊,應該顯示編輯選項ContextMenu。但是,我無法執行右鍵單擊操作。而且在點擊編輯菜單後,我應該能夠在文本框中顯示數據。例如NotesID應該顯示在textbox1中。C#datagridview右鍵單擊選擇編輯選項,數據應顯示在文本框中

/*this is for datagrid cell click code*/ 
private void dataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    ContextMenuStrip mnu = new ContextMenuStrip(); 
    ToolStripMenuItem mnuedit = new ToolStripMenuItem("Edit"); 
    mnuedit.Click += new EventHandler(editToolStripMenuItem_Click); 
    mnu.Items.AddRange(new ToolStripItem[] { mnuedit }); 
    dataGrid1.ContextMenuStrip = mnu; 
} 

private void editToolStripMenuItem_Click(object sender, EventArgs e) 
{ 

    if (dataGrid1.SelectedRows.Count == 0) 
    { 
     textnotes.Text = Convert.ToString(dataGrid1.SelectedRows[0].Cells[0].Value); 
     textclient.Text = Convert.ToString(dataGrid1.SelectedRows[0].Cells[1].Value); 
     textdatetime.Value = Convert.ToDateTime(dataGrid1.SelectedRows[0].Cells[2].Value); 
     textcombobox.Text = Convert.ToString(dataGrid1.SelectedRows[0].Cells[3].Value); 
    } 
} 

private void EditClient_Click(object sender, EventArgs e) 
{ 
} 

private void textBox2_TextChanged(object sender, EventArgs e) 
{ 
} 

private void SaveButton_Click(object sender, EventArgs e) 
{ 
    Service edtservice = new Service(); 
         edtservice.EditNotes(Convert.ToInt32(textNotesID.Text),textnotes.Text,textclient.Text,textdatetime.Text,textcombobox.Text); 
    MessageBox.Show("Records Updated"); 
} 

回答

1

嘗試發射它的鼠標事件

private void dgvReport_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
{ 

    If (e.Button = MouseButtons.Right){ 

     DataGridViewRow row = this.dgvReport.Rows[e.rowIndex]; 

    } 

} 
+0

當我用鼠標右鍵單擊單元格,我可以看到上下文菜單選項,編輯。但是當我點擊編輯我得到錯誤作爲參數OUTOFRangeeption未處理。下面是該代碼:: –

+0

私人無效editToolStripMenuItem_Click(對象發件人,EventArgs的) { 如果(dataGrid1.SelectedRows.Count == 0){ textnotes.Text = Convert.ToString(dataGrid1.SelectedRows [ 0] .Cells [0]。價值); textclient.Text = Convert.ToString(dataGrid1.SelectedRows [0] .Cells [1] .Value); } –

+1

使用e.rowIndex和e.Column索引來獲取您的行和單元格,超出範圍將異常將selectedRows沒有索引在您指定的值。 – CR41G14

相關問題