2017-02-24 136 views
1

嗨,我想隐藏或禁用我第三列中的按钮,我打算每次单击它时添加行。乱七八糟的是,以前的按钮是活动的,可以添加行。我怎样才能把按钮放在最后一行?如何在DataGridView中禁用或隐藏按钮

这是我的工作代码:

Private Sub dgAppliances_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgAppliances.CellContentClick 
    If e.ColumnIndex <> 2 Then 
     Exit Sub 
    Else 
     If Me.dgAppliances.RowCount - 1 = 20 Then 
      MsgBox("Maximum of 20 appliances only.") 
     Else 
      Me.dgAppliances.Rows.Add() 
     End If 
    End If 
End Sub 

但是,当我加入了一些代码:

Private Sub dgAppliances_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgAppliances.CellContentClick 
    If e.ColumnIndex <> 2 Then 
     Exit Sub 
    Else 
     If Me.dgAppliances.RowCount - 1 = 20 Then 
      MsgBox("Maximum of 20 appliances only.") 
     Else 
      Me.dgAppliances.Rows.Add() 
      Dim cell As DataGridViewButtonCell = dgAppliances.Rows(0).Cells(2) 
      cell.Value = String.Empty 
      cell = New DataGridViewColumn() 
      cell.ReadOnly = True 
     End If 
    End If 
End Sub 

此行电池=新的DataGridViewColumn()有错误。

它说'System.Windows.Forms.DataGridViewColumn'不能转换为'System.Windows.Forms.DataGridViewButtonCell'。

任何人都可以帮助我吗? TIA。

Here's the sample image.

回答

0

你试图分配一个DataGridViewColumnDataGridViewButtonCell - 整个到一个细胞

也许你的意图是:cell = New DataGridViewTextBoxCell()?但即便如此,如果你只在最后一排

试图

地方的按钮,然后你会碰上Adding Different DataGridView Cell Types to a Column问题。你可以做如下转换:

Me.dataGridView1.ColumnCount = 3 
Me.dataGridView1.AllowUserToAddRows = False 
Me.dataGridView1.AllowUserToDeleteRows = False 
Me.dataGridView1.RowCount = 1 
Me.dataGridView1(2, 0) = New DataGridViewButtonCell() 

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataGridView1.CellContentClick 
    If TypeOf Me.dataGridView1(e.ColumnIndex, e.RowIndex) Is DataGridViewButtonCell Then 
     If Me.dataGridView1.RowCount - 1 = 20 Then 
      MessageBox.Show("Maximum of 20 appliances only.") 
     Else 
      Me.dataGridView1.Rows.Add() 
      Me.dataGridView1(e.ColumnIndex, e.RowIndex) = New DataGridViewTextBoxCell() 
      Me.dataGridView1(e.ColumnIndex, e.RowIndex).[ReadOnly] = True 
      Me.dataGridView1(e.ColumnIndex, Me.dataGridView1.RowCount - 1) = New DataGridViewButtonCell() 
     End If 
    End If 
End Sub 
+0

哇。你是最好的!!十分感谢你的帮助。 :)))它的工作原理,我正在努力使以前的行删除按钮。 :)非常感谢你,希望你也能帮助我。 :) –

+0

在这种情况下,根本不需要转换单元格。从头开始将该列设置为“DataGridViewButtonColumn”。然后在你的'CellContentClick'事件中,如果你点击一个'DataGridViewButtonCell',检查它是否是网格中的最后一行。如果是,请添加另一行。如果不是,请删除点击的行。唯一需要使用的部分是将按钮文本从“添加”更改为“删除”。 – OhBeWise

+0

我知道了,先生。再次感谢你。 :)) –