7

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();
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
momal
  • 576
  • 2
  • 13
  • 30

6 Answers6

7
if( 0 == dtStock.Rows.Count ) // does not exist
Moho
  • 15,457
  • 1
  • 30
  • 31
3

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.

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
2

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")
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2

You can do something like this

    If(dtStock.Rows.Count > 0) 
    {
    //code goes here
    dataGridView1.DataSource = dtStock;
    }
    else
    {
    //Record not exists
    }
Gajendra
  • 1,291
  • 1
  • 19
  • 32
2

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 + "')"
Nick.Mc
  • 18,304
  • 6
  • 61
  • 91
1
 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;
    }
RON12345
  • 123
  • 1
  • 3
  • 10