5

我想有一个DataGridView有两列。第一列将始终是DataGridViewComboBoxColumn类型。基于该列中的选择,我希望能够将第二列中的相应单元格更改为DataGridViewComboBoxCell或DataGridViewTextBoxCell。如何在DataGridViewTextBoxCell和DataGridViewComboBoxCell之间切换?

我在想我只需要使DataGridViewColumn类型的第二列,但不理解如何在飞行中更改单元格类型的机制。

我与VB.NET工作在Visual Studio提前2005

谢谢!

更新:它周围的一种方式,我想,是使第二列作为DataGridViewComboBoxColumn,并改变细胞的特性,使其无论是行为就像一个下拉列表,或作为(编辑)没有元素的下拉菜单。后者看起来就像一个我可以忍受的文本框,它不会涉及改变单元格的类型。

回答

3

我没有VB.Net版本,但希望这个快速的C#代码段可以帮助您或者指出您朝着正确的方向发展。

在这个例子中,我设置了一个简单的DataGridView和2列。第一个是填充了两个选项的DataGridViewComboBox:“文本”或“组合”。

第二列最初设置为来自设计者的DataGridViewTextBoxColumn。

我处理DataGridView上的CurrentCellDirtyStateChanged事件。我检查单元是否脏,只检查第一列(组合框)。您必须致电CommitEdit以获得组合中的新值,否则您将查看先前的值。根据组合框中的选择,然后使用该类型的新单元格覆盖第二列中的单元格。

您将添加自己的逻辑(填充下拉列表并处理该值)。您可能想要存储该值,然后将其放回到单元格中或其他内容中。

这里是我使用,并做了一个快速和肮脏的测试代码:

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) 
    { 
     if (dataGridView1.IsCurrentCellDirty == false) 
     { 
      return; 
     } 

     dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); 

     if (dataGridView1.CurrentCell.ColumnIndex == 0) 
     {    
      if (((string)dataGridView1.CurrentCell.Value) == "Text") 
      { 
       dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewTextBoxCell(); 
      } 
      else if (((string)dataGridView1.CurrentCell.Value) == "Combo") 
      { 
       dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewComboBoxCell(); 
      } 
     } 
    } 

下面是一个简单的VB的翻译,我测试和工程。

Public Class Form1 

Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged 

    If DataGridView1.IsCurrentCellDirty = False Then 
     Return 
    End If 

    DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit) 

    If DataGridView1.CurrentCell.ColumnIndex = 0 Then 

     If CStr(DataGridView1.CurrentCell.Value) = "Text" Then 
      DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewTextBoxCell 

     ElseIf CStr(DataGridView1.CurrentCell.Value) = "Combo" Then 
      DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewComboBoxCell 
     End If 

    End If 


End Sub 

末级

你将失去​​存储在该列的任何值,所以你需要先将其保存。

Jon

+0

谢谢。这很有帮助。我不是一个真正的VB或者一个。NET专家,所以我原则上看到你在做什么,但是在VB中分配新的DataGridViewTextBoxCell或新的DataGridViewComboBoxCell的机制是我仍然必须弄清楚的。无论如何,我很欣赏你把答案写入你的答案,今天下午我会试一试。 – John 2009-11-23 17:51:38

+0

工程很好。谢谢! – John 2009-11-25 00:57:06

2

您可以创建自己的托管用户控件的单元模板。在用户控件中添加一个文本框和一个组合框,并添加一个方法/属性来显示一个并隐藏另一个。

This sample创建单选按钮单元格,不难更改代码以承载用户控件。

0
dgvCell = new DataGridViewTextBoxCell();   // code to remove checkbox 
     dgvCell.Value = string.Empty; 
     dgv_modi_del_trans.Rows[1].Cells[0] = dgvCell;