2017-04-19 63 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