在组合框选择后使用mysql数据填充文本框

时间:2014-02-16 09:29:49

标签: mysql sql vb.net combobox textbox

所以我有2个mysql表,一个名为“Service_Details”,一个名为“Payment_details”

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

我收到错误''[0]的'标识符'和'值类型'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

1 个答案:

答案 0 :(得分:0)

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的创建,作为适配器的一个局部变量它没有意义或效果(如果这是你在这个事件中的所有代码)。

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

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