2017-02-22 166 views
-1

我有以下代码,它从Devexpress Datagrid中删除空行。从网格删除空行

Private Sub btnRemoveBlanks_ItemClick(sender As Object, e As ItemClickEventArgs) Handles btnRemoveBlanks.ItemClick 
    Try 
    Dim I As Integer 
     For I = 0 To StudentsGrid.DataRowCount - 1 
      Dim CellValue As Object = StudentsGrid.GetRowCellValue(I, "FirstName") 
     If String.IsNullOrWhiteSpace(CellValue.ToString) = True OrElse CellValue Is Nothing OrElse CellValue Is DBNull.Value Then 
      ' Debug.Print("Empty") 
      StudentsGrid.DeleteRow(I) 
     Else 
      ' Debug.Print("Not Empty") 
     End If 
     Next 
    StudentsGrid.RefreshData() 
    btnRefresh.PerformClick() 
    Catch ex As Exception 
    MessageBox.Show(ex.Message, "Error: " & System.Reflection.MethodBase.GetCurrentMethod.Name, MessageBoxButtons.OK, MessageBoxIcon.Error) 
    End Try 
End Sub 

然而,一个问题是,我接收

对象引用不设置为一个对象的一个​​实例。

上线起点:if string.isnullorwhitespace

或者我必须点击该按钮两次或三次,除去所有的空白。

有没有更好的方法来确定行是空的还是空白的?任何想法我可能会改进这个代码?

编辑:主要的原因问题是去除空白,这我能够向后步进通过网格

+2

如果IsDBNull以便(CellValue)OrElse运算CellValue是Nothing OrElse运算... – Aaron

+1

你需要重新安排你的支票让'CellValue为Nothing '先来...如果它为空,你不能检查它的'ToString()'方法。您还需要向后循环而不是向前循环,否则一旦删除一行,您的索引值将不同步。如果您必须前进,您必须在删除后手动调整'i'的值 – pinkfloydx33

回答

2

你想要两个不同的事情要做:

  1. 的空引用异常可以通过重新排序If命令中的条件来解决。
  2. 需要重新运行删除多次是由于您如何遍历行。您的For循环迭代至网格视图中的行数。假设您目前正在查看第4行并决定将其删除。现在前索引5的行取这个位置(每一行的索引减1)。在下一次迭代中,您会看到索引5,该索引现在是索引为6的行,这意味着您将永远不会查看原始第五行。为了解决这个问题反向你的循环

试试这个稍微改变版本的代码(未经测试):

Private Sub btnRemoveBlanks_ItemClick(sender As Object, e As ItemClickEventArgs) Handles btnRemoveBlanks.ItemClick 
    Try 
     Dim rowIdx as Integer = StudentsGrid.DataRowCount - 1 
     For i as Integer = rowIdx To 0 Step -1 
      Dim CellValue As Object = StudentsGrid.GetRowCellValue(I, "FirstName") 
      If CellValue Is Nothing OrElse IsDBNull(CellValue) OrElse String.IsNullOrWhiteSpace(CellValue.ToString()) Then 
       ' Debug.Print("Empty") 
       StudentsGrid.DeleteRow(i) 
      Else 
       ' Debug.Print("Not Empty") 
      End If 
     Next 
     StudentsGrid.RefreshData() 
     btnRefresh.PerformClick() 
    Catch ex As Exception 
     MessageBox.Show(ex.Message, "Error: " & System.Reflection.MethodBase.GetCurrentMethod.Name, MessageBoxButtons.OK, MessageBoxIcon.Error) 
    End Try 
End Sub