2013-04-19 17 views
5

Questo è il mio codice per visualizzare/cercare un record in una tabella di database. Come faccio a mettere una convalida se il roecord esiste o no? Sta cercando attraverso l'ID di un membro. come dovrei mostrare un messaggio se il record non esiste?Come posso verificare se la riga esiste o no?

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

risposta

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

Is [un'estensione] (http://stackoverflow.com/a/34438198/2404470) utile? – xameeramir

2

È possibile utilizzare in questo modo:

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

Vedi Here & Here. Come utilizzare Dataset e DataTables.

2

È possibile utilizzare la proprietà DataRowCollection.Count.

Ottiene il numero totale di oggetti DataRow in questa raccolta.

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

Si può fare qualcosa di simile

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

Questa SQL verrà probabilmente sarà molto più veloce, in quanto restituisce solo 0 o 1 righe al cliente, piuttosto che ogni riga corrispondente e ogni singola colonna. Prendi l'abitudine di usare *

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

Ok. Lo farò. Grazie. – YehCheez

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; 
    } 
Problemi correlati