如何在c#中为标题禁用datagridview鼠标单击事件

时间:2014-04-25 20:20:50

标签: c# datagridview click mouse

我试图通过鼠标点击事件从datagridview中获取价值。

在我点击datagridview中的标题之前效果很好。我收到一个错误说:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name:index

我使用此代码检测鼠标点击:

 private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView1.Rows[e.RowIndex].Index != -1)
            {
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
            else
            {
                textBox1.Text = "";
            }
        }
  

" dataGridView1.Rows [e.RowIndex] .Index!= -1"   没有工作,我不知道为什么。

在标题上禁用鼠标点击事件的任何简单解决方案都会很棒!谢谢!

我也用:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

选择整列,CellContentClick不起作用。如果我很幸运,CEllContentClick可以工作3/10次。

1 个答案:

答案 0 :(得分:3)

请尝试改写:

private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex != -1)
    {
        textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    }
    else
    {
        textBox1.Text = "";
    }
}
相关问题