Checking if a datatable is null
As of C# 6.0 you can use the Null conditional operator ?.
(or ?[]
for arrays).
The null conditional operator simplifies the statement to:
if (dt?.Rows?.Count > 0)
This returns false when:
- the data table
dt
is null - data table Rows
dt.Rows
is null - the number of rows
dt.Rows.Count
is 0
Using the null conditional operator you can avoid manually checking both the data table and count properties, eg if (dt != null && dt.Rows.Count > 0)
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.
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
}
}
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.