Checking if a datatable is null

后端 未结 7 1848
南旧
南旧 2021-02-19 22:02

The following code is what I\'ve been using to retrieve user information from a sql database.

            string userName = LoginUser.UserName;
            strin         


        
相关标签:
7条回答
  • 2021-02-19 22:16

    You will get an empty DataTable if no records match, so you can check on the number of records returned:

    if (dt.Rows.Count > 0)
    

    And, slightly off topic, please read the comments below your question, then Google the terms SQL Injection and Parameterized SQL statements. Try starting with this.

    0 讨论(0)
  • 2021-02-19 22:17

    It seems to me using a DataTable and SqlDataAdapter is a little bit too heavy for the task.

    You can just use a DataReader here:

            SqlCommand command = new SqlCommand(comm, conn);
            using (var reader = command.ExecuteQuery()) 
            {
                if (reader.Read())
                {
                    //logic
                    var userName = reader.GetString(0);
                    var password = reader.GetString(1);
                    // etc
                }
            }
    
    0 讨论(0)
  • 2021-02-19 22:20

    Why not just change the statement a bit to see if the DataTable is either null or has no rows:

    if(dt != null && dt.Rows.Count > 0)
    

    Also, on a side note, you should look into Parameterized Queries as well rather than building your SQL dynamically. It will reduce the number of attack vectors for attackers trying to compromise your application.

    0 讨论(0)
  • 2021-02-19 22:21

    For DataSet you can check like this:

    if (ds.Tables[0].Rows.Count > 0)
    
    0 讨论(0)
  • 2021-02-19 22:21

    I know this question IS OLD and the answers helped at the moment it was published, but there is an easy way to solve this right now as follows:

    if ((dataTableName?.Rows?.Count ?? 0) > 0)
    
    0 讨论(0)
  • 2021-02-19 22:33

    It will be better if you use try catch for checking whether the table is empty or not , just handle the IndexOutOfRangeException exception.

    Use the following logic:

    try
    {
       //dataTable operations
    }
    catch(IndexOutOfRangeException)
    {
    }
    

    For me its working.

    0 讨论(0)
提交回复
热议问题