获得特别的最高记录

时间:2019-05-29 21:32:56

标签: vb.net

我在Table1中有3个字段(IdFactory类型为Numeric-IdSector类型为Numeric-NameFactory类型为Text)。当我单击Button1时,我在TextBox1中获得了(IdFactory)的最大记录。我的ComboBox1填充了从1到100.我通过ComboBox1选择(IdSector),该字段(IdSector)中的记录仅重复5次。当我单击Button1时,如何自动在combobox1中显示(IdSector)的最大记录。这是我的代码,可以在TextBox1

2 个答案:

答案 0 :(得分:0)

ExecuteScalar返回Nothing,如果未找到结果,则返回DBNull.Value

Dim result As Object = Cmd.ExecuteScalar
Dim id As Integer
If result Is Nothing Then
    id = 1
Else
    id = CInt(result)  + 1
End If
TextBox1.Text = id.ToString()
ComboBox1.SelectedItem = id

这假定您已将数字作为Integer而不是String添加到组合框。如果您已将它们添加为String,请执行ComboBox1.SelectedItem = id.ToString()

答案 1 :(得分:0)

将数据对象保留在本地,以便确保它们已关闭并处置。即使出现错误,“使用...结束使用”块也会为您执行此操作。

我想您需要的是拥有最高IdFactory的IdSector。尽管您不能在where子句中使用聚合函数;您可以使用带有汇总的子查询。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim result As Object
    Using Conne As New OleDbConnection("Your connection string")
        Using Cmd As New OleDbCommand("Select IdSector from Table1 Where IdFactory = (Select max(IdFactory) From Table1);", Conne)
            Conne.Open()
            result = Cmd.ExecuteScalar
        End Using
    End Using
    If result Is Nothing Then
        TextBox1.Text = "1"
        ComboBox1.Text = "1"
    Else
        TextBox1.Text = (CInt(result) + 1).ToString
        ComboBox1.Text = result.ToString
    End If
End Sub