Reputation:
ive made a search function for my C# console app, and it works just great! But when i search for a product that does not exist, it just returns blank.. i would like to test if there are actually any hits, and if not, write it out to the user, and if there are hits, show the result like normal.
My search function:
public List<Product> SearchProduct(string searchresult)
{
SqlConnection conn = Database.openConnection();
List<Product> products = new List<Product>();
using SqlCommand command = new SqlCommand(@"SELECT * FROM Products WHERE (ProductName Like @ProductName);", conn);
{
command.Parameters.AddWithValue("@ProductName", "%" + searchresult + "%");
using SqlDataReader reader = command.ExecuteReader();
Console.Clear();
Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}", "ID:", "Produkt:", "Antal:", "SubKategori:", "Sidst redigeret af:\n");
while (reader.Read())
{
// Checking if reader has a value..
if (string.IsNullOrEmpty(reader.ToString()))
{
Console.WriteLine("No product with that criteria..\n");
}
Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}",
reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
Console.WriteLine("\nTryk vilkårlig tast for at returnere");
Console.ReadLine();
Console.Clear();
conn.Close();
}
return products;
}
Upvotes: 0
Views: 185
Reputation: 38785
Change your loop to a do
/while
and check the result for the initial reader.Read()
before entering the loop:
bool canRead = reader.Read();
if (canRead)
{
do
{
// Checking if reader has a value..
if (string.IsNullOrEmpty(reader.ToString()))
{
Console.WriteLine("No product with that criteria..\n");
}
Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}",
reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
while (canRead = reader.Read());
}
else
{
Console.WriteLine("No rows found.");
}
Alternatively, populate your products
list and check products.Count
once the loop is complete (as per Esko's comment).
Upvotes: 1