使用TextBox显示记录

时间:2018-05-14 21:37:20

标签: vb.net

使用此代码,要显示的随机记录的数量是固定的,并在命令文本中进行硬编码(" Top 10")。如何从代码中删除数字(前10名)并将其替换为TextBox1的值,并编写我想在Datagridview1中显示的可变记录数?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DataBase_Connection()
    InfoCommand = New OleDbCommand(" SELECT Top 10 ID, First_Name, Last_Name FROM FACTORY ORDER BY RND(-(100000*ID)*Time())", ConStr)
    InfoAdapter = New OleDbDataAdapter()
    InfoAdapter.SelectCommand = InfoCommand
    InfoTable = New DataTable()
    InfoAdapter.Fill(InfoTable)
    DataGridView1.DataSource = InfoTable
End Sub

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的要求,以下内容应该可以正常工作:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim rows As Integer
    If Not Integer.TryParse(TextBox1.Text, rows) Then
        ' Invalid number. You can display a MessageBox or something.
        Exit Sub
    End If

    DataBase_Connection()
    ' Works with VS2015 and above:
    'Dim sql As String = $"SELECT Top {rows} ID, First_Name, Last_Name FROM FACTORY ORDER BY RND(-(100000*ID)*Time())"

    ' Works with VS2013 and below:
    Dim sql As String = String.Format("SELECT Top {0} ID, First_Name, Last_Name FROM FACTORY ORDER BY RND(-(100000*ID)*Time())",
                                      rows)
    InfoCommand = New OleDbCommand(sql, ConStr)
    InfoAdapter = New OleDbDataAdapter()
    InfoAdapter.SelectCommand = InfoCommand
    InfoTable = New DataTable()
    InfoAdapter.Fill(InfoTable)
    DataGridView1.DataSource = InfoTable
End Sub

其中Integer.TryParse()用于验证输入是否为整数值。

参考文献: