【问题标题】:Populate a textbox with mysql data after a combobox selection选择组合框后用 mysql 数据填充文本框
【发布时间】:2014-03-15 14:10:54
【问题描述】:

所以我有 2 个 mysql 表,一个叫做“Service_Details”,一个叫做“Payment_details”

我的表单中有一个组合框,它显示服务表中的“service_id”字段。 我正在尝试编写一个文本框,因此当我从组合框中选择服务 ID 时,它会写入“服务”,这是我的服务详细信息表中的另一个字段。服务 ID 与服务相关联。

我在 [0] 处收到错误 'identifier expected' 和 'system.data.datatablecollection' 类型的值无法在 dss.tables 转换为 'string'

浏览了一个小时后,我似乎无法正常工作

这是我的代码:

Private Sub cbxserviceid_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxserviceid.SelectedIndexChanged
    Dim dss As New DataSet
    Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID='" + cbxserviceid.Text + "'", objconnection)
    Dim cmddd = New MySqlCommandBuilder(daa)
    daa.Fill(dss)
    txtService1.Text = dss.Tables[0].Rows[0]["Service"].ToString();
End Sub

【问题讨论】:

    标签: mysql sql vb.net combobox textbox


    【解决方案1】:

    VB.NET中的索引用圆括号表示,方括号用C#表示

    txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
    

    同时避免对 sql 命令文本使用字符串连接,始终使用参数化查询

    Private Sub cbxserviceid_SelectedIndexChanged(......)
        Dim dss As New DataSet
        if cbxserviceid.SelectedIndex <> -1 Then
            Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID=@id", _
                                            objconnection)
            daa.SelectCommand.Parameters.AddWithValue("@id",  Convert.ToInt32(cbxserviceid.Text))
            daa.Fill(dss)
            txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
        End If
    End Sub
    

    我还删除了 MySqlCommandBuilder 的创建,将适配器作为一个局部变量,它没有任何意义或影响(当然,如果这是您在此事件中的所有代码)。

    查看下面的 cmets 和与发帖者的聊天,还有另一个错误需要修复。 在为组合框分配 DataSource、DisplayMember 和 ValueMember 属性时,必须遵循精确的顺序以避免不必要的副作用

    cbxserviceid.DisplayMember = "ServiceID"
    cbxserviceid.ValueMember = "ServiceID"
    cbxserviceid.DataSource = datatable
    

    【讨论】:

    • 我收到错误在命令执行期间遇到致命错误。 daa.fill(dss) ?
    • 对不起,我没有注意到你的第一条评论。字段ServiceID是MySql中的字符串(文本)还是整数?
    • TinyInt(自动增量)
    • 那么我们需要将参数值转换为整数(或短整数),更新答案。如果可能的话,也试试 Convert.ToInt16
    • 我现在得到 Input string was not in a correct format on daa.SelectCommand.Parameters.AddWithValue("@id", Convert.ToInt32(cbxserviceid.Text)) Input16 throws same error
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多