The following code is what I\'ve been using to retrieve user information from a sql database.
string userName = LoginUser.UserName;
strin
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.
For DataSet
you can check like this:
if (ds.Tables[0].Rows.Count > 0)
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)
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.