How to check if a string exists or not?

This is my code for displaying / searching records in a database table. How can I check if a tuple exists or not? He is looking for a member id. How should I show the 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();
+7
source share
6 answers
if( 0 == dtStock.Rows.Count ) // does not exist
+6
source

You can use the following:

If(dtStock.Rows.Count > 0) // If dtStock.Rows.Count == 0 then there is no rows exists.
{
    // Your Logic
}

See here and here . How to use DatasetandDataTables.

+2
source

DataRowCollection.Count.

DataRow .

If(0 == dtStock.Rows.Count)
  Console.WriteLine("There are no rows in that datatable")
+2

-

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

SQL, , , 0 1 , . *

SELECT  1 As X WHERE EXISTS (
    Select 1 from Members where Number = '" + SearchID.Text + "')"
+2
 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;
    }
+1
source

All Articles