2012-12-04 61 views
20

我在我的C#应用​​程序中有一个datagridview,用户应该只能点击完整的行。所以我将SelectionMode设置为FullRowSelect。c#datagridview双击FullRowSelect的行

但是现在我想要在用户双击一行时触发一个事件。我想要在MessageBox中有行号。

我试过如下:

this.roomDataGridView.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.roomDataGridView_CellCont‌ ​entDoubleClick); 

private void roomDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) 
{ 
     MessageBox.Show(e.RowIndex.ToString()); 
} 

Unforunately没有任何反应。我究竟做错了什么?

+1

你怎么订阅双击事件? –

+1

在设计器中,我编写this.roomDataGridView.CellContentDoubleClick + = new System.Windows.Forms.DataGridViewCellEventHandler(this.roomDataGridView_CellContentDoubleClick); – Metalhead89

+0

我刚刚删除了我的活动,并再次执行此操作,现在它可以正常工作。我真的不知道发生了什么,但它现在起作用 – Metalhead89

回答

6

在Visual Studio中,通常会导致头痛,不要手动编辑.designer文件。而是在DataGridRow的属性部分中指定它应该包含在DataGrid元素中。或者,如果您只是想让VS为您找到属性页面中的双击事件(事件(小闪电图标)),然后双击要输入该事件的函数名称的文本区域。

这个链接应该帮助

http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx

3

这将工作,确保您的控件事件分配给此代码,它可能已经丢失,我也注意到,双击将只在单元格不为空时才起作用。尝试与内容的单元格双击,不惹设计师

private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) 
{ 

    //do something 


} 
11

在CellContentDoubleClick事件触发仅当单元格的内容双击。我用这个和工作原理:

private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
    { 
     MessageBox.Show(e.RowIndex.ToString()); 
    } 
2

您使用Northwind数据库员工表作为例子得到在DataGridView行的索引号:

using System; 
using System.Windows.Forms; 

namespace WindowsFormsApplication5 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      // TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed. 
      this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees); 

     } 

     private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
     { 
      var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString(); 
      string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); 

      MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: " 
       + cellValue.ToString()); 
     } 
    } 
} 

的结果会告诉你记录的索引号和datagridview中第二个表列的内容:

enter image description here