如何使用 SelectionChanged 事件检查是否在 datagridview 中单击了列标题

Har*_*ter 3 c# datagridview winforms

我正在使用 a 的SelectionChanged事件DataGridView。我有一个代码可以将 aDataGridView的单元格的值显示到 a TextBox。但是,当我单击列标题时,这也会触发代码(我假设是因为SelectionChanged事件)并显示错误。

我想要实现的是将我的代码包含在datagridview1_SelectionChangedinif语句中。其中:

if(column header is clicked)    
    //don't do anything`    
else    
    //do the display of data to textbox`
Run Code Online (Sandbox Code Playgroud)

我只想知道检查您是否单击标题的代码。

DiS*_*teR 8

只需检查事件

List_SelectionChanged(object sender, EventArgs e)
{ 
     if(e.Rowindex>-1)
        ...
}
Run Code Online (Sandbox Code Playgroud)

-1 用于标题


Sal*_*ari 6

您可以检查您的DataGridView'sCurrentRow是否为空。如果它不为空,则表示您尚未单击列标题:

private void yourDataGridView_SelectionChanged(object sender, EventArgs e)
{
    var current = yourDataGridView.CurrentRow;
    if (current != null) // Means that you've not clicked the column header
    {
        //Display the value of a DataGridView's cell to a TextBox    
    }
}
Run Code Online (Sandbox Code Playgroud)