Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if row exists or not?

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();
like image 815
momal Avatar asked Apr 19 '13 05:04

momal


4 Answers

if( 0 == dtStock.Rows.Count ) // does not exist
like image 154
Moho Avatar answered Oct 07 '22 00:10

Moho


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.

like image 22
RajeshKdev Avatar answered Oct 06 '22 23:10

RajeshKdev


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")
like image 32
Soner Gönül Avatar answered Oct 06 '22 23:10

Soner Gönül


You can do something like this

    If(dtStock.Rows.Count > 0) 
    {
    //code goes here
    dataGridView1.DataSource = dtStock;
    }
    else
    {
    //Record not exists
    }
like image 36
Gajendra Avatar answered Oct 07 '22 01:10

Gajendra