2017-10-11 66 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

相关问题