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");
}
當我用鼠標右鍵單擊單元格,我可以看到上下文菜單選項,編輯。但是當我點擊編輯我得到錯誤作爲參數OUTOFRangeeption未處理。下面是該代碼:: –
私人無效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); } –
使用e.rowIndex和e.Column索引來獲取您的行和單元格,超出範圍將異常將selectedRows沒有索引在您指定的值。 – CR41G14