这是我在数据库表中显示/搜索记录的代码。如何判断是否存在roecord?它正在搜索成员的ID。如果记录不存在,我应该如何显示消息?
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();
答案 0 :(得分:6)
if( 0 == dtStock.Rows.Count ) // does not exist
答案 1 :(得分:2)
您可以这样使用:
If(dtStock.Rows.Count > 0) // If dtStock.Rows.Count == 0 then there is no rows exists.
{
// Your Logic
}
答案 2 :(得分:2)
您可以使用DataRowCollection.Count
属性。
获取此集合中DataRow对象的总数。
If(0 == dtStock.Rows.Count)
Console.WriteLine("There are no rows in that datatable")
答案 3 :(得分:2)
你可以做这样的事情
If(dtStock.Rows.Count > 0)
{
//code goes here
dataGridView1.DataSource = dtStock;
}
else
{
//Record not exists
}
答案 4 :(得分:2)
这个SQL可能会快得多,因为它只返回0或1行到客户端,而不是每个匹配的行和每一列。摆脱使用*
的习惯SELECT 1 As X WHERE EXISTS (
Select 1 from Members where Number = '" + SearchID.Text + "')"
答案 5 :(得分: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;
}