This is my code to display/search a record in a database table. How do I put a validation whether the roecord exists or not? It is searching through the ID of a member. how should I show a message if the record does not exist?
string connectionstring = "Server=Momal-PC\\MOMAL;Database=Project;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionstring;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * from Members where Number = '" + SearchID.Text + "'", conn);
DataTable dtStock = new DataTable();
sda.Fill(dtStock);
dataGridView1.DataSource = dtStock;
conn.Close();
if( 0 == dtStock.Rows.Count ) // does not exist
You can use like this:
If(dtStock.Rows.Count > 0) // If dtStock.Rows.Count == 0 then there is no rows exists.
{
// Your Logic
}
See Here & Here. How to use Dataset
and DataTables.
You can use DataRowCollection.Count
property.
Gets the total number of DataRow objects in this collection.
If(0 == dtStock.Rows.Count)
Console.WriteLine("There are no rows in that datatable")
You can do something like this
If(dtStock.Rows.Count > 0)
{
//code goes here
dataGridView1.DataSource = dtStock;
}
else
{
//Record not exists
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With