在我的应用程序中,我有一个数据绑定ComboBox
,如下所示:
Dim listaCategoria As List(Of Ccategoria) = CAD.ObterTodosC()
cbxAlterarCg.DataSource = listaCategoria
cbxAlterarCg.DisplayMember = "nomeCategoria"
cbxAlterarCg.ValueMember = "idCategoria"
班级代码(CAD):
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
属性:
Public Class Ccategoria
Private _idCategoria As Integer
Private _nomeCategoria As String
(...)
我的ComboBox
显示“nomeCategoria”,其中“idCategoria”值为right。
现在我的问题,就像标题所说我可以创建一个默认的只读项目,所以说(“选择你的类别”)或类似的东西?
我已经看过其他一些教程,但是ComboBox
都没有数据限制。
答案 0 :(得分:1)
您可以做的是在Ccategoria()
下lstTodos
添加Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
,如下所示:
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
这样做只需添加DataSource
即可。然后,您可以通过检查idCategoria
是否为0来查看提供验证。如果是,您可能需要考虑向用户显示MessageBox
,提示他们选择一个类别。