检测DataGridView中是否至少选中了一个单元格

问题描述:

我使用ToolStripButton创建了DataGridView和BindingNavigator表单。 所以我需要禁用一个BindingNavigator的ToolStripButton,当任何一个单元格被选中并且在至少有一个单元格被选中时启用它。 我已经尝试过CellClick事件和SelectionChanged事件,但我无法解决此问题。检测DataGridView中是否至少选中了一个单元格

private void myDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e) 
{ 
if (myGridView.Columns[e.ColumnIndex].Name == "findValueDataGridViewTextBoxColumn" 
        || myDataGridView.Columns[e.ColumnIndex].Name == "replaceValueDataGridViewTextBoxColumn") 
       { 
        myDropDownButton.Enabled = true; 
       } 
       else 
       { 
        myDropDownButton.Enabled = false; 
       } 
} 

任何想法如何做到这一点?

+0

那你试试这么远吗? – Paolo 2014-10-08 07:01:28

+0

你可以告诉你代码,也许可能是我们可以为你编辑? – 2014-10-08 07:01:30

+1

“选择”是什么意思?如果你的意思是正确的话,那么显而易见的是'SelectedCells'集合是你需要查看的地方。如果你的意思是别的,那么这将有助于解释。 – jmcilhinney 2014-10-08 07:07:06

使用索引而不是名称和DataGridViewCellCancelEventArgs代替DataGridViewCellEventArgs。

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
{ 
    string msg = String.Format("Editing Cell at ({0}, {1})", 
     e.ColumnIndex, e.RowIndex); 
//You go to your datagrid and identify the index of the replaceValueDataGridViewTextBoxColumn 
//e.g Int ColIndex1 = replaceValueDataGridViewTextBoxColumn index 0 fro the first , 1 for second etc. 
    if(e.ColumnIndex = ColIndex1 || e.ColumnIndex = ColIndex2) 
    { 
     myDropDownButton.Enabled = true; 
    } 
    // this.Text = msg; 
} 

在你的情况

private void myDataGridView_CellEnter(object sender, DataGridViewCellCancelEventArgs e) 
{ 
//get the column index of your columns 
//Here you dont need to call grid name just e is enough 
//Note you can try e.Name may be , but i didn't 
if (e.ColumnIndex == colIndex1 || e.ColumnIndex == colIndex2) 
    { 
      myDropDownButton.Enabled = true; 
    } 
    else 
    { 
      myDropDownButton.Enabled = false; 
     } 
} 

或尝试像下面,把一个破发点,看到COLNAME的价值。

private void dataGridView1_CellMouseEnter(object sender, 
    DataGridViewCellEventArgs e) 
{ 
    string colName= (string)dataGridView1.Columns[e.ColumnIndex].Name 
} 

请检查HereHere为完整的解释。

您可以使用DataGridViewSelectedCells属性:

if (myDataGridView.SelectedCells.Count > 1) // at least one cell selected 
{ 
    //do somethings 
}