Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查行是否存在?_C#_Sql Server_Database - Fatal编程技术网

C# 如何检查行是否存在?

C# 如何检查行是否存在?,c#,sql-server,database,C#,Sql Server,Database,这是我在数据库表中显示/搜索记录的代码。如何验证roecord是否存在?它正在搜索成员的ID。如果记录不存在,我应该如何显示消息 string connectionstring = "Server=Momal-PC\\MOMAL;Database=Project;Trusted_Connection=True;"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connectionstring; con

这是我在数据库表中显示/搜索记录的代码。如何验证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();

您可以这样使用:

If(dtStock.Rows.Count > 0) // If dtStock.Rows.Count == 0 then there is no rows exists.
{
    // Your Logic
}
见&。如何使用
数据集
数据表。

您可以使用属性

获取此集合中DataRow对象的总数


你可以这样做

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

这种SQL可能会快得多,因为它只向客户端返回0或1行,而不是每个匹配的行和每一列。改掉使用电脑的习惯*

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

可以我会这样做的。非常感谢。
    If(dtStock.Rows.Count > 0) 
    {
    //code goes here
    dataGridView1.DataSource = dtStock;
    }
    else
    {
    //Record not exists
    }
SELECT  1 As X WHERE EXISTS (
    Select 1 from Members where Number = '" + SearchID.Text + "')"
 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;
    }