简体   繁体   English

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

[英]how to disable datagridview mouse click event for headers in c#

I am trying to get value out of datagridview on mouse click event. 我正在尝试从datagridview的鼠标单击事件中获取价值。

Works great until I click on headers in datagridview. 在我单击datagridview中的标题之前,效果很好。 I get an error saying: 我收到一条错误消息:

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

I use this code to detect mouse click: 我使用以下代码来检测鼠标单击:

 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" doesn't work and I do not know why. “ dataGridView1.Rows [e.RowIndex] .Index!= -1”不起作用,我也不知道为什么。

Any easy solution to disable mouse click event on headers would be great! 任何简单的在标题上禁用鼠标单击事件的解决方案都很棒! Thanks! 谢谢!

I also use: 我还使用:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

to select whole column and CellContentClick doesn't work. 选择整个列,CellContentClick不起作用。 If I am lucky, CEllContentClick works 3/10 times. 如果幸运的话,CEllContentClick可以运行3/10次。

Try writing this instead: 尝试编写以下代码:

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 = "";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM