2017-06-03 57 views
1

通过rowspaned小区中所有受影响的行我有以下选择上的DataGridView

我要的是,当我选择BOX00099电池,三排右被选中。 此外,当我选择这三行之一,其他两行和BOX00099被选中。 所以,这个想法是将所有三行都视为一行。

+0

显示实际的代码 – Max

+0

这是一个Windows窗体应用程序,这并不重要我怎么填充datagridview,这只是在SelectionChange事件中的技巧。 – Adnand

+0

[阅读本文](https://stackoverflow.com/help/mcve) – Max

回答

0

我解决了这个问题,并为那些谁可能有同样的问题,因为我,这就是我做的:

我用了一个扩展的datagridview而不是普通的一个。

public partial class DataGridViewEx : DataGridView 
{ 
    public DataGridViewEx() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnPaint(PaintEventArgs pe) 
    { 
     base.OnPaint(pe); 
    } 

    protected override void SetSelectedRowCore(int rowIndex, bool selected) 
    { 
     this.SuspendLayout(); 
     base.SetSelectedRowCore(rowIndex, selected); 
     int index = rowIndex; 
     while (index < this.Rows.Count - 1 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index + 1].Cells["BoxNo"].Value.ToString()) 
     { 
      base.SetSelectedRowCore(index + 1, selected); 
      index = index + 1; 
     } 
     index = rowIndex; 
     while (index > 0 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index - 1].Cells["BoxNo"].Value.ToString()) 
     { 
      base.SetSelectedRowCore(index - 1, selected); 
      index = index - 1; 
     } 
     this.ResumeLayout(); 
    } 
} 

然后我添加从this project列。该项目有一个演示,所以你有一个例子如何使用它。跨越一个小区,我用

var cell = (DataGridViewTextBoxCellEx)dataGridView1[0, index]; 
      int nr = (int)dataGridView1.Rows[index].Cells["Nr"].Value; 
      cell.RowSpan = nr; 

之后,从“3 spaned行”去到另一行与键上/下,我已经按上/下钮3次(选择每。排一个接一个地从“3 spaned行”为了解决这个问题,我用它的按键事件如上:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (dataGridView1.Rows.Count > 0) 
     { 
      int current = dataGridView1.CurrentRow.Index; 
      if (e.KeyData == Keys.Down) 
      { 
       e.Handled = true; 
       dataGridView1.SuspendLayout(); 
       for (int i = current; i < dataGridView1.Rows.Count; i++) 
       { 
        if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString()) 
        { 
         dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"]; 
         break; 
        } 
       } 
       dataGridView1.ResumeLayout(); 
      } 
      else if (e.KeyData == Keys.Up) 
      { 
       e.Handled = true; 
       dataGridView1.SuspendLayout(); 
       for (int i = current; i >= 0; i--) 
       { 
        if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString()) 
        { 
         dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"]; 
         break; 
        } 
       } 
       dataGridView1.ResumeLayout(); 
      } 
     } 
    }