2017-10-11 67 views
0

用戶不應該能夠在datagridview中的單元格爲空的情況下輸入數量。如何在第二個單元格爲空的情況下使單元格只讀

爲了說清楚,我想讓單元格readonly = true,如果單元列是空的。

colUOM4是列的名稱,如果該列的單元格爲空,則olNewQty2單元格將爲只讀的。

我想這個代碼,但沒有奏效

Public Sub UnitEmpty() 
    For i As Integer = 0 To dgvCount.RowCount - 1 
     If dgvCount.Rows(i).Cells("colUOM4").Value Is Nothing Then 
      MessageBox.Show("Its Worked!") 
      dgvCount.Rows(i).Cells("colNewQty2").ReadOnly = True 
     Else 
      MessageBox.Show("Nothing happened!") 

      Exit For 
     End If 
    Next 
End Sub 

this is my datagridview and the name for it is dgvCount

回答

1

我建議不使用一個循環,因爲這將只設置狀態,當你執行它並不會響應任何變化。我建議在行和單元級別工作,即當添加一行時設置默認狀態,然後在特定單元改變時作出反應,例如,

Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded 
    For i = e.RowIndex To e.RowIndex + e.RowCount - 1 
     'Make the first cell in each new row read-only by default. 
     DataGridView1(0, i).ReadOnly = True 
    Next 
End Sub 

Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged 
    'Check whether the change is in the second column. 
    If e.RowIndex >= 0 AndAlso e.ColumnIndex = 1 Then 
     Dim row = DataGridView1.Rows(e.RowIndex) 

     'Make the first cell in the row read-only if and only if the second cell is empty. 
     row.Cells(0).ReadOnly = (row.Cells(1).Value Is Nothing) 
    End If 
End Sub 
+0

感謝您的回覆,我會馬上試試。 –

+0

它沒有工作..它仍然可以編輯另一列,即使第二列單元格爲空 –

+0

我直接從一個測試項目中爲我工作的代碼,所以我懷疑你做錯了什麼。我從一個空格開始,直接輸入新的行。在這種情況下它適合你嗎?當它不起作用時,你究竟做了什麼? – jmcilhinney

相關問題