使用VB.Net
我想使用3层架构
为表格值填充组合框代码。
DAL
Public Function Combo1(ByVal cmb1select As string) As SqlDataReader
cmd = New SqlCommand("Select Name from table1", con)
dr = cmd.ExecuteReader
While (dr.Read())
cmb1select = (dr("Name"))
End While
Return dr
End Function
BLL
Public Function combo1(ByVal cmb1select As String) As SqlDataReader
dr = New New_DAL().Combo1("cmb1select")
Return dr
End Function
UL
combobox1.Items.Add(New New_BLL().combo1("cmb1select"))
上面的代码正在运行,但我在combobox中得到一个值为“System.Data.SQLclinet.SQL”
它不显示数据。
我的代码出了问题。
需要vb.net代码帮助
答案 0 :(得分:1)
抱歉,我忘了测试我的代码。无论如何,我确实模拟了你的情况,发现你无法在你的UI中获得datareader结果,因为必须在DAL层关闭(因为你返回了datareader对象)。另一种方法是使用数据库并将其绑定在组合框控件上。我对您的代码进行了一些修改并尝试了它并发现它正常工作。这就是我所做的:
在DAL层:
Public Class New_DAL
Public Function Combo1(ByVal cmb1select As String) As DataTable
'Not included in the snippet a assume it is coded this way
Dim cmd As SqlClient.SqlCommand
Dim con As SqlClient.SqlConnection
Dim dr As SqlClient.SqlDataReader
con = New SqlClient.SqlConnection("your_connection_string")
con.Open()
'----------
'New Code
Dim dt As New DataTable
dt.Columns.Add("Name")
'----------
cmd = New SqlClient.SqlCommand("Select Name from table1", con)
dr = cmd.ExecuteReader
While (dr.Read())
'old code
'cmb1select = (dr("Name"))
'New Code
dt.Rows.Add(dr("Name"))
'----------
End While
'Not included in the snippet a assume it is coded this way
con.Close()
'----------
'old code
'Return dr
Return dt
End Function
End Class
在BLL层:
Public Class New_BLL
Public Function combo1(ByVal cmb1select As String) As DataTable
'New code
Dim dt As DataTable
'----------
'Old code
'dr = New New_DAL().Combo1("cmb1select")
dt = New New_DAL().Combo1("cmb1select")
'Old Code
'Return dr
Return dt
End Function
End Class
在UI图层
ComboBox1.DataSource = New New_BLL().combo1("cmb1select")
ComboBox1.DisplayMember = "Name"
我对它进行了测试并找到了工作(因为我没有你的数据库,所以我自己的连接字符串以及select语句中的不同字段和表格):)
答案 1 :(得分:0)
您只需将DisplayMember设置为“名称”即可。默认情况下,控件调用ToString()并显示类型名称。