2011-09-26 136 views
1

我在窗体中有一个DataGridView。功能如下。如何在DataGridView中选择多个单元格

  • 单击标题选择整个列。
  • 点击比列标题之外的任何细胞选择整个行

我已多选设置为true。我可以通过使用鼠标来选择多个单元格。但我想以编程方式进行。

回答

6

如果您有多项选择真正为您DataGridView,那么你可以通过电网和设置所需的行作为Selected

环(还您dataGridView.SelectionMode应该是FullRowSelect

dataGridView.Rows[0].Selected = true;//determine index value from your logic 
dataGridView.Rows[5].Selected = true; 

编辑

而不是行选择,那么你可以尝试这个逻辑,订阅rowheaderclick事件,其中你会得到它被点击的行索引,现在循环遍历列并设置每个单元格被选中(与上面类似)

对于HeaderClick事件,您可以使用列索引的相同方式,现在循环行并设置选定的行索引。

datagridview1[columnindex, rowindex].Selected = true 

对于行rowindex将被固定,而对于列选择columnindex将是固定的。

希望这可以帮助你。

+0

感谢您的回复。但上述方法不能解决问题,因为我必须单击列标题来选择整个列。如果SelectionMode设置为“FullRowSelect” – Bimal

+0

检查我的编辑这应该与CellSelect模式工作 – V4Vendetta

+0

这工作。谢谢 – Bimal

0

在尝试选择(多个)项目之前,允许DataGridView完成加载其数据非常重要。您可以在DataBindingComplete事件处理程序中执行此操作。 下面是一个工作示例:

List<int> items = new List<int>() { 2, 4 }; 
    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 
     dataGridView1.ClearSelection(); 

     int lastItem = 0; // Save the last match to scroll to it later 
     bool cellSelected = false; 

     for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--) 
     { 
      if (items.Contains((int)dataGridView1.Rows[i].Cells[0].Value)) 
      { 
       lastItem = i; 

       dataGridView1.Rows[i].Selected = true; 

       if (!cellSelected) // gotta select only one cell 
       { 
        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; 
        cellSelected = true; 
       } 
      } 
     } 

     dataGridView1.FirstDisplayedScrollingRowIndex = lastItem; 
    } 
相关问题