1、DataGridView中实现右键单击后选中所在行及弹出上下文菜单
首先对dataGridView1添加RowContextMenuStripNeeded事件,然后新建一个DataGridViewRow,通过e.RowIndex捕获鼠标右键单击的行信息,清除所有选中的行,将鼠标右键捕获到的行设为选中。
在这里通过dataGridViewRow1.Cells["fullNameDataGridViewTextBoxColumn"].Value将所选单元格的内容传给变量,附代码如下。
private void dataGridView1_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)
{
DataGridViewRow dataGridViewRow1 = dataGridView1.Rows[e.RowIndex];
dataGridView1.ClearSelection();
dataGridViewRow1.Selected = true;
toolStripMenuItem1.Enabled = true;
fullName = dataGridViewRow1.Cells["fullNameDataGridViewTextBoxColumn"].Value as string;
// if ((dataGridViewRow1.Cells["Title"].Value.ToString() ==
//"Sales Manager") ||
//(dataGridViewRow1.Cells["Title"].Value.ToString() ==
//"Vice President, Sales"))
// {
// e.ContextMenuStrip = managerMenuStrip;
// }
// else
// {
// e.ContextMenuStrip = employeeMenuStrip;
// }
// contextMenuRowIndex = e.RowIndex;
}
--------------------------------------------------------------------------------------------
2、DataGridView中通过事件捕获所选行的ID号及单元格内容
主要是通过dataGridView1.Rows[dataGridView1.CurrentCellAddress.Y].Cells["列名"].Value捕获鼠标单击的行及指定列的值。
fullName = dataGridView1.Rows[dataGridView1.CurrentCellAddress.Y].Cells["fullNameDataGridViewTextBoxColumn"].Value as string;
if (fullName != null)
{
MessageBox.Show(fullName);
}
--------------------------------------------------------------------------------------------