How to check empty DataTable

后端 未结 8 585
孤城傲影
孤城傲影 2020-12-10 10:15

I have a DataSet where I need to find out how many rows has been changed using the following code:

dataTable1 = dataSet1.Tables[\"FooTable\"].Ge         


        
相关标签:
8条回答
  • 2020-12-10 10:41

    Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.

    if (DetailTable != null && DetailTable.Rows.Count>0)
    
    0 讨论(0)
  • 2020-12-10 10:47

    Don't use rows.Count. That's asking for how many rows exist. If there are many, it will take some time to count them. All you really want to know is "is there at least one?" You don't care if there are 10 or 1000 or a billion. You just want to know if there is at least one. If I give you a box and ask you if there are any marbles in it, will you dump the box on the table and start counting? Of course not. Using LINQ, you might think that this would work:

    bool hasRows = dataTable1.Rows.Any()
    

    But unfortunately, DataRowCollection does not implement IEnumerable. So instead, try this:

    bool hasRows = dataTable1.Rows.GetEnumerator().MoveNext()
    

    You will of course need to check if the dataTable1 is null first. if it's not, this will tell you if there are any rows without enumerating the whole lot.

    0 讨论(0)
  • 2020-12-10 10:52

    If dataTable1 is null, it is not an empty datatable.

    Simply wrap your foreach in an if-statement that checks if dataTable1 is null. Make sure that your foreach counts over DataTable1.Rows or you will get a compilation error.

        if (dataTable1 != null)
        {
           foreach (DataRow dr in dataTable1.Rows)
           {
              // ...
           }
        }
    
    0 讨论(0)
  • 2020-12-10 10:54
    Sub Check_DT_ForNull()
    Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value
    If Not WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value = "" Then
       Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Rows.Count
    End If
    End Sub
    

    This checks the first row value in the DataBodyRange for Null and Count the total rows This worked for me as I downloaded my datatable from server It had not data's but table was created with blanks and Rows.Count was not 0 but blank rows.

    0 讨论(0)
  • 2020-12-10 10:55

    You can also simply write

     if (dt.Rows.Count == 0)
         {
             //DataTable does not contain records
         }        
    
    0 讨论(0)
  • 2020-12-10 10:56

    First make sure that DataTable is not null and than check for the row count

    if(dt!=null)
    {
      if(dt.Rows.Count>0)
      {
        //do your code 
      }
    }
    
    0 讨论(0)
提交回复
热议问题