帮助组合框 [英] help with combobox

查看:88
本文介绍了帮助组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是vb的新手.我试图根据组合框中的所选项目从数据库中获取文本框的值.
任何人都可以告诉我以下代码有什么问题吗?

I am new to vb. I am trying to get a value for a textbox from a database according to the selected item in combobox.
Could anyone please tell me what is wrong with the following code?

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
  Dim connstrg As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Documents and Settings\hedris\My Documents\REGISTER.mdb;"
  Dim conn As New OleDbConnection(connstrg)
  Try
    conn.Open()
    Dim DA1 As New OleDbDataAdapter("select* FROM CLARUS where product=" & ComboBox1.SelectedItem & "", conn)
    Dim ds1 As New DataSet
    Dim dt As New DataTable
    DA1.Fill(ds1, "clarus")
    dt = ds1.Tables("clarus")
    conn.Close()
    TextBox1.Text = dt.Rows.Item(0).Item(0)
  Catch ex As Exception
    MsgBox(ex.Message)
  End Try
End Sub

推荐答案

您的Clarus表中的Product字段是数字字段还是文本字段?如果是后者,我不会感到惊讶,因为您没有将值包装在引号中,例如

Is the Product field in your Clarus table a numeric field or a text field? If the latter, I''m not surprised you are having a problem as you are not wrapping the value in quotes e.g.

"SELECT * FROM Clarus WHERE (Product = ''" & ComboBox1.SelectedItem & "'')"



无论哪种情况,最好使用参数化查询,例如:



In either case it would be better to use a parameterised query such as:

Dim DA1 As New OleDbDataAdapter("SELECT * FROM Clarus WHERE (Product = ?)", conn)
DA1.Parameters.AddWithValue("@Product", ComboBox1.SelectedItem)



这样您就不必担心Product字段中包含什么类型的数据.



as you then don''t have to worry about what type of data is contained in the Product field.


在上面的代码中,您有一条语句

In your code above you have the statement

Dim DA1 As New OleDbDataAdapter("select* FROM CLARUS where product=" & ComboBox1.SelectedItem &
"", conn)



分成两行.那是如何显示在您的源文件中?如果是这样,则需要在第一行的末尾添加下划线"_"字符



split over two lines. is that how it appears in your source file? If so, you need to append an underscore ''_'' character to the end of the first line

Dim DA1 As New OleDbDataAdapter("select* FROM CLARUS where product=" & ComboBox1.SelectedItem & _
"", conn)



因此,VB.NET编译器知道该语句在第二行继续.



so the VB.NET compiler knows that the statement is continued on the second line.


ComboBoxSelectedItem属性是Object而不是String.要将其用作字符串连接的一部分,您需要显式调用ToString方法:

The SelectedItem property of a ComboBox is an Object not a String. To use it as part of a string concatenation, you need to explicitly invoke the ToString method:

"select* FROM CLARUS where product = ''" & ComboBox1.SelectedItem.ToString() & "''"


这篇关于帮助组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆