momal
momal

Reputation: 587

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();

Upvotes: 7

Views: 17329

Answers (6)

RON12345
RON12345

Reputation: 123

 public static int RowCount()
        {

            string sqlConnectionString = @" Your connection string";
            SqlConnection con = new SqlConnection(sqlConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) AS Expr1 FROM Tablename", con);
            int result = ((int)cmd.ExecuteScalar());
            con.Close();
            return result;
    }

Upvotes: 1

Nick.Mc
Nick.Mc

Reputation: 19184

This SQL will be likely be much faster, as it will only return 0 or 1 rows to the client, rather than every matching row and every single column. Get out of the habit of using *

SELECT  1 As X WHERE EXISTS (
    Select 1 from Members where Number = '" + SearchID.Text + "')"

Upvotes: 2

Rajeshkumar Kandhasamy
Rajeshkumar Kandhasamy

Reputation: 6461

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.

Upvotes: 3

Gajendra
Gajendra

Reputation: 1291

You can do something like this

    If(dtStock.Rows.Count > 0) 
    {
    //code goes here
    dataGridView1.DataSource = dtStock;
    }
    else
    {
    //Record not exists
    }

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98750

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")

Upvotes: 2

Moho
Moho

Reputation: 16498

if( 0 == dtStock.Rows.Count ) // does not exist

Upvotes: 7

Related Questions