DataTable Filter神秘

时间:2010-04-12 15:19:09

标签: asp.net vb.net

你能帮我找到我找到的神秘的原因吗? 在下面的代码中,我创建了一个DataTable并对其进行过滤。当我使用filter1时,一切都按预期工作。 当我使用filter2时,只有SubsectionAmount变量小于10时,一切都按预期工作。 一旦我设置SubsectionAmount = 10,dr2数组就会返回Nothing。 我找不到有什么不对。这是代码:

Imports System.Data

Partial Class FilterTest     继承System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Call FilterTable()
End Sub

Sub FilterTable()
    Dim dtSubsections As New DataTable
    Dim SectionID As Integer, SubsectionID As Integer
    Dim SubsectionAmount As Integer
    Dim filter1 As String, filter2 As String
    Dim rowID As Integer
    Dim dr1() As DataRow, dr2() As DataRow

    With dtSubsections
        .Columns.Add("Section")
        .Columns.Add("Subsection")
        .Columns.Add("FieldString")

        SectionID = 1
        SubsectionAmount = 10 '9
        For SubsectionID = 1 To SubsectionAmount
            .Rows.Add(SectionID, SubsectionID, "abcd" & CStr(SubsectionID))
        Next SubsectionID

        For rowID = 0 To .Rows.Count - 1
            Response.Write(.Rows(rowID).Item(0).ToString & " " _
                           & .Rows(rowID).Item(1).ToString & " " _
                           & .Rows(rowID).Item(2).ToString & "<BR>")
        Next
        SubsectionID = 1
        filter1 = "Section=" & SectionID & " AND " & "Subsection=" & SubsectionID
        filter2 = "Section=" & SectionID & " AND " & "Subsection=" & SubsectionID + 1

        dr1 = .Select(filter1)
        dr2 = .Select(filter2)

        Response.Write(dr1.Length & "<BR>")
        Response.Write(dr2.Length & "<BR>")
        If dr1.Length > 0 Then
            Response.Write(dr1(0).Item("FieldString").ToString & "<BR>")
        End If
        If dr2.Length > 0 Then
            Response.Write(dr2(0).Item("FieldString").ToString & "<BR>")
        End If
    End With
End Sub

结束班

2 个答案:

答案 0 :(得分:1)

该行

"Section=" & SectionID & " AND " & "Subsection=" & SubsectionID + 1

看起来很狡猾(?)

考虑这段代码:

var i = 2;
string j = "Hello " + i + 1;

当您打印 j 时,您将获得“Hello21”而不是“Hello3”。应用于字符串的+运算符将接受右侧的任何对象,并通过调用对象上的ToString()来使用它们,从而使您的int有效地成为字符串。现在,我假设在VB.Net中它非常相似,可能不是你想要的。

<强>更新 显然VB.Net以不同的方式做事,所以很乐意忽略......

答案 1 :(得分:1)

将列添加语句更改为以下内容,以便正确进行比较。

    .Columns.Add("Section", GetType(Integer))
    .Columns.Add("Subsection", GetType(Integer))
    .Columns.Add("FieldString")