■■■

2016年3月31日木曜日

DataGridViewのセルの値を行単位でチェックする方法

DataGridViewのセルの値を行単位でチェックする方法
VB.NET
Private Sub dgv1_RowValidating(ByVal sender As Object, _
ByVal e As DataGridViewCellCancelEventArgs) _
Handles dgv1.RowValidating

Dim dgv As DataGridView = DirectCast(sender, DataGridView)
If e.RowIndex = dgv.NewRowIndex OrElse Not dgv.IsCurrentRowDirty Then
Exit Sub
End If


For Each cell As DataGridViewCell In dgv.Rows(e.RowIndex).Cells
If cell.Value Is Nothing OrElse cell.Value.ToString() = "" Then
dgv.Rows(e.RowIndex).ErrorText = _
"セルに値を入力してください"
e.Cancel = True
End If
Next
End Sub


Private Sub dgv1_RowValidated(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles dgv1.RowValidated

Dim dgv As DataGridView = DirectCast(sender, DataGridView)
dgv.Rows(e.RowIndex).ErrorText = Nothing
End Sub
C#
private void dgv1_RowValidating(object sender,
DataGridViewCellCancelEventArgs e)
{
DataGridView dgv = (DataGridView)sender;

if (e.RowIndex == dgv.NewRowIndex || !dgv.IsCurrentRowDirty)
{
return;
}

foreach (DataGridViewCell cell in dgv.Rows[e.RowIndex].Cells)
{
if (cell.Value == null || cell.Value.ToString() == "")
{
dgv.Rows[e.RowIndex].ErrorText =
"セルに値を入力してください";
e.Cancel = true;
}
}
}

private void dgv1_RowValidated(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
dgv.Rows[e.RowIndex].ErrorText = null;
}




















■■■