当Combobox值更改出错时运行函数

时间:2014-11-11 16:22:49

标签: database vb.net combobox

当组合框中的值发生变化时,我正试图显示来自数据库的数据,但我正在

Input string was not in a correct format.

projectName = Integer.Parse(ComboBox1.ValueMember)

这是我的代码

Public Class Total_Amount_Report

    Private Sub Total_Amount_Report_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        sql = "SELECT SUM([Total Amount]) as totalAmount FROM pt_funds"



        Dim da As New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "TotalAmounts")
        ComboBox1.DataSource = ds.Tables("TotalAmounts")
        ComboBox1.DisplayMember = "Project Name"
        ComboBox1.ValueMember = "ID"



    End Sub

    Private Sub Combobox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
        Dim projectName As Integer
        Dim sql2 As String

        projectName = Integer.Parse(ComboBox1.ValueMember)

        sql2 = "SELECT * FROM pt_funds WHERE ID=" & projectName & " "
        Dim da1 As New OleDb.OleDbDataAdapter(sql2, con)
        da1.Fill(ds, "ProjectAmount")
        Label3.Text = ds.Tables("ProjectAmount").Rows(0).Item("Total Amount")
    End Sub

End Class

2 个答案:

答案 0 :(得分:0)

您是否尝试将String数字转换为整数?如果是这样的话:

projectName = CInt(ComboBox1.ValueMember)

我相信Integer.Parse适用于VB.net而非VBA

答案 1 :(得分:0)

不是ComboBox1.ValueMember您从ComboBox1.SelectedValue获得了价值。Object。它以CInt的形式返回,因此Public Class Form1 Dim dt As DataTable Sub FillCB() dt = New DataTable dt.Columns.Add(New DataColumn With {.ColumnName = "Project Name", .DataType = Type.GetType("System.String")}) dt.Columns.Add(New DataColumn With {.ColumnName = "ID", .DataType = Type.GetType("System.Int32")}) Dim projNames As New List(Of String) From {"A", "B", "C"} Dim projIds As New List(Of Integer) From {17, 19, 25} For i = 0 To projNames.Count - 1 Dim nr = dt.NewRow nr.Item(0) = projNames(i) nr.Item(1) = projIds(i) dt.Rows.Add(nr) Next ' remove the SelectedIndexChanged temporarily as it interferes RemoveHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged ComboBox1.DataSource = dt ComboBox1.DisplayMember = "Project Name" ComboBox1.ValueMember = "ID" AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged End Sub Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Dim cb = CType(sender, ComboBox) If cb.SelectedIndex >= 0 Then Dim projectID As Integer = CInt(cb.SelectedValue) MsgBox(projectID.ToString()) End If End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load FillCB() End Sub End Class 是从中获取整数值的最简单方法。

为了演示,我将ComboBox放在新的Windows窗体上并使用以下代码:

{{1}}