简体   繁体   English

c# 数据表行计数为空表返回 1

[英]c# datatable row count returns 1 for empty table

I'm querying a SQL Server database and filling a datatable.我正在查询 SQL 服务器数据库并填写数据表。 But even when my sql returns no values, the datatable row count seems to be one.但即使我的 sql 没有返回任何值,数据表的行数似乎也是一。 Here's my code:这是我的代码:

strSQL = "My sql string"
cmd.CommandText = strSQL;
cmd.Parameters.AddWithValue("@wsNo", wsNo);
cmd.Parameters.AddWithValue("@reachNo", reachNo);
using (DataTable dt = new DataTable())
    {
        dt.Load(cmd.ExecuteReader());
        MyTextbox.Text = dt.Rows.Count.ToString();
        myGridview.DataSource = dt;
        myGridview.DataBind();
    }

The gridview displays the data correctly, and doesn't display at all if the sql returns no records. gridview 正确显示数据,如果 sql 没有返回记录,则根本不显示。 But I want to display the record count in a textbox, and that's always 1 when there are no records.但我想在文本框中显示记录数,当没有记录时,它总是 1。 A couple of places I've checked imply that ExecuteReader might be the wrong tool for this job, but if so, it isn't clear to me what I should be usi我检查过的几个地方暗示 ExecuteReader 可能是这项工作的错误工具,但如果是这样,我不清楚我应该使用什么

EDIT: I rebuilt this code using a data adapter, and it seems to be working now.编辑:我使用数据适配器重建了这段代码,它现在似乎可以工作了。 I don't see why, shouldn't make a difference, but I guess rewriting the code fixed whatever I was doing wrong.我不明白为什么,不应该有所作为,但我想重写代码修复了我做错的任何事情。 No further comments necessary.无需进一步评论。 Thanks to people who replied.感谢回复的人。

Typically you will want to fill your DataSet with DataAdapters.通常,您会希望用 DataAdapter 填充您的 DataSet。 You don't need a DataTable to bring back one record with a DataReader.您不需要 DataTable 来使用 DataReader 带回一条记录。 But here's how you can do it:但您可以这样做:

DataTable dt = new DataTable("TableName");

using (connection)
{
    SqlCommand command = new SqlCommand(sSQL, connection);
    connection.Open();

    using (SqlDataReader reader = command.ExecuteReader())
    {
        dt.Load(reader);
    }
}

YourControl.Text = dt.Rows.Count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM