2017-04-19 149 views
1

我在我的DataGridView中有DataGridViewButtonCell,我想将属性Visible设置为True如何隐藏DataGridViewButtonCell

我曾尝试:

DataGridView1.Rows("number of row i want").Cells("number of cell i want").Visible = True 

不幸的是,它说,物业visibleread only

这里是代码

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick 
     'does not work 
     DataGridView1.Rows(e.RowIndex).Cells(6).Visible = True   
End Sub 

有谁知道我怎么能做到这一点?

谢谢。

+0

的[有时候我想隐藏在DataGridViewButtonColumn按钮](可能的复制http://stackoverflow.com/questions/25200679/sometimes-i-want-to-hide-buttons-in-a -datagridviewbuttoncolumn) – JohnG

+0

您可以将启用设置为false,或者干脆忽略您想要禁用的按钮的点击事件。 – JohnG

+0

都是.NET的'DataGridViewButtonColumn' – JohnG

回答

0

没有实际的方法来隐藏DataGridViewButtonCell。目前我只能看到两个选项:

  1. 使用填充按钮移动按钮,如图所示here。我将提供类似的VB.NET代码
  2. CellDataGridViewTextBoxCellReadOnly属性设置为

使用Padding

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick 
    If DataGridView1.Rows(e.RowIndex).Cells(6).GetType() Is GetType(DataGridViewButtonCell) Then 
     Dim columnWidth As Integer = DataGridView1.Columns(e.ColumnIndex).Width 

     Dim newDataGridViewCellStyle As New DataGridViewCellStyle With {.Padding = New Padding(columnWidth + 1, 0, 0, 0)} 

     DataGridView1.Rows(e.RowIndex).Cells(6).Style = newDataGridViewCellStyle 
    End If 
End Sub 

使用DataGridViewTextBoxCell

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick 
    If DataGridView1.Rows(e.RowIndex).Cells(6).GetType() Is GetType(DataGridViewButtonCell) Then 
     Dim newDataGridViewCell As New DataGridViewTextBoxCell 

     DataGridView1.Rows(e.RowIndex).Cells(6) = newDataGridViewCell 

     newDataGridViewCell.ReadOnly = True 
    End If 
End Sub 

这两个应该给你的效果不显示按钮

+1

谢谢我使用DataGridViewTextBoxCell,它完美地工作,谢谢你! –

+0

@哈马哈拉不是问题,很高兴它有帮助。 – Bugs

1

这真是一个透视问题。从程序员的角度来看,只需忽略按钮上的按钮,我想要禁用这些按钮就非常容易,只需要几行代码。

从用户的角度来看,这种情况会发生这样的情况......用户点击看起来有效的按钮,什么也没有发生。用户没有为此编写代码...所以用户最好会认为计算机没有响应按钮点击或最坏的情况...会认为你的编码技能是可疑的!

如果按钮丢失,也会发生同样的情况。用户不会知道为什么它会丢失......但很可能会得出与上面所述的非工作按钮相同的结论。

在另一个非常简单的方法中,假设所有按钮都已启用,并且我们有一个我们要禁用的按钮索引列表。用户按下其中一个按钮,我们检查禁用的按钮列表,并且如果点击的按钮是禁用的按钮,则只需显示一个消息框以指示禁用此按钮的原因。这种方法对用户说...“这里有一堆按钮,猜猜哪些是启用的”...

DataGridViewDisableButtonCellDataGridViewDisableButtonColumn包装解决所有上述问题...该按钮是可见的,因此用户不会问,按钮在哪里如果你将它设置为隐形并且变灰,就会去。 “灰色”是大多数用户可以理解的,并且将减轻用户不得不“猜测”哪些按钮被启用。

您可以为两个类创建包装:DataGridViewButtonCell和DataGridViewButtonColumn。

到MS示例的链接How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control是我在使用C#之前使用过的一个,但是在链接上也有一个VB实现。

下面是使用MS链接中描述的两个包装的结果的图片。为了测试,下面的图片使用按钮左侧的复选框来禁用右侧的按钮。

恕我直言,使用这种策略是用户友好的。如果你只是简单地让按钮不可见或只读,那么用户可能会认为你的代码搞砸了,并且不清楚按钮为什么缺失或不起作用。禁用的按钮向用户指示该按钮不可用于该项目。一个选项是让鼠标翻转指出按钮被禁用的原因。

enter image description here

+0

我认为通过禁用按钮看起来比移除或隐藏它好。这是OP应该做的。 – Bugs