简体   繁体   中英

how to check Datagridview column if empty or not in vb.net

Please anyone can help me. May I ask how to check if the entire specific column in the datagridview has a value or not using vb.net

I tried different ways but I didn't get what i want.

i use this code but it only check the current cell not the entire column

    If (String.IsNullOrWhiteSpace(mainform.DataGridView2.CurrentCell.Value.ToString())) Then
        MsgBox("Empty")
    Else
        MsgBox("Not Empty")
    End If

This is my sample data in the datagirdview

Try this

 For i = 0 To dgv.RowCount - 1

            If String.IsNullOrEmpty(dgv.Item("columnname", i).Value) Then

            End If

          

        Next

All

To get whether all the cells of a given column have values:

Using LINQ:

Dim col = 1 'Or name
Dim allHaveValues = YourDataGridView.Rows.OfType(Of DataGridViewRow).
    Where(Function(r) Not r.IsNewRow).
    All(Function(r) r.Cells.OfType(Of DataGridViewTextBoxCell).
    Where(Function(c) c.OwningColumn.Index = col AndAlso 
    If(c.Value?.ToString(), String.Empty).Trim().Length > 0).Any())

MessageBox.Show(If(allHaveValues, "Yes", "No"))

Or, For Each loop:

Dim col = "ColumnName"
Dim allHaveValues = True

For Each row As DataGridViewRow In YourDataGridView.Rows
    If Not row.IsNewRow Then
        If If(row.Cells(col).Value?.ToString(), String.Empty).Trim().Length = 0 Then
            allHaveValues = False
            Exit For
        End If
    End If
Next

MessageBox.Show(If(allHaveValues, "Yes", "No"))

Any

In contrast, if you need to get if any cell has value:

LINQ:

Dim anyHasValue = YourDataGridView.Rows.
    OfType(Of DataGridViewRow).
    Where(Function(r) Not r.IsNewRow AndAlso r.Cells.
    OfType(Of DataGridViewTextBoxCell).
    Any(Function(c) c.OwningColumn.Index = col AndAlso
    If(c.Value, String.Empty).ToString().Trim().Length > 0)).
    Any()

MessageBox.Show(If(anyHasValue, "Yes", "No"))

Loop:

Dim col = 1
Dim anyHasValue = False

For Each r As DataGridViewRow In YourDataGridView.Rows
    If Not r.IsNewRow Then
        If If(r.Cells(col).Value, String.Empty).ToString().Length > 0 Then
            anyHasValue = True
            Exit For
        End If
    End If
Next

MessageBox.Show(If(anyHasValue, "Yes", "No"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM