【问题标题】:datatable row count shows 1 even when there are no records present即使没有记录,数据表行数也显示为 1
【发布时间】:2013-11-17 06:08:00
【问题描述】:

我将检索到的值返回到一个变量中,但在检查行是否存在之后。但是 if 条件失败,因为表中当前没有记录。

    Dim sqlstr as string
    Dim da As SqlClient.SqlDataAdapter
    sqlstr = "select max(mat_req_no) as mat_req_no from pos_mrq_hdr"

    If dt.Rows.Count > 0 Then
        ltino = dt.Rows(0)("mat_req_no").tostring

    End If


    the if dt.rows.count > 0 

【问题讨论】:

  • 忘记添加此语句.. da = New SqlClient.SqlDataAdapter(sqlstr, AppsCon) da.Fill(dt)..
  • dt.rows.count > 0 失败,因为没有行但它仍然返回超过 1。
  • 你能把你的完整代码吗?

标签: sql vb.net winforms


【解决方案1】:

您可能会忘记代码中的某些语句,但是当我在Max 中进行测试时,它会在行数中始终返回 (1),因此我们应该测试返回值是否为 NULL 或 NOT

完整的代码将是

Imports System.IO
Imports System.Data.SqlClient
Public Class Form1
Dim cnn As SqlConnection
Dim connectionString As String
Dim sqlAdp As SqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataSet

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=userid; Password=password"
    cnn = New SqlConnection(connectionString)
    cnn.Open()
    sqlAdp = New SqlDataAdapter("select max(mat_req_no) as mat_req_no from pos_mrq_hdr", cnn)
    cnn.Close() 'connection close here , that is disconnected from data source
    sqlAdp.Fill(ds)
    sqlAdp.Fill(dt)
    'fetching data from dataset in disconnected mode
    ' MsgBox(ds.Tables(0).Rows.Count)
    If IsDBNull(ds.Tables(0).Rows(0).Item(0)) Then
        '    MsgBox("no")
    Else
        Dim ltino = ds.Tables(0).Rows(0)("mat_req_no").ToString
        '  MsgBox(ltino)
    End If
End Sub
    End Class

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2018-08-14
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多