即使数据源为空,使用数据源的Windows窗体刷新ComboBox也会保留值

时间:2014-06-24 13:14:51

标签: asp.net vb.net combobox

我有2个组合框,cmbstud和cmbhostel。它们通过将数据源绑定到数据表来从数据库中填充。在我更新时,cmbstud会相应更新。当我更新最后一条记录时,数据表清空,但cmbstud仍然保留该值。 Cmbhostel数据必然会改变cmbstud的索引。

在表单加载事件中,我有以下代码:

Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
    dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
sqlcont.Conn.Close()

在我的btnhostel进行更新时,我实现了以下查询,并使用以下代码重新加载表单以刷新我的数据源:

"UPDATE hostel SET in_use=in_use+1 WHERE hostel_id=@hostid"
"UPDATE student_details SET hostel_id=@hostid where stud_id=@stud_id"
frmallocateHostel_Load(Nothing, Nothing)

Cmbstud索引更改evnt代码:

Dim sqcm5 As New SqlCommand("Select hostel.hostel_id,hostel.hostel_name From hostel Inner Join student_details On student_details.gender = hostel.hostel_gender where student_details.stud_id =" & cmbstud.SelectedValue.ToString & " ", sqlcont.Conn)
Dim datreadr5 As SqlDataReader = sqcm5.ExecuteReader
Dim dt5 As New DataTable
Dim n As Integer
For n = 0 To dt5.Rows.Count - 1
    datreadr5.Read()
Next
dt5.Load(datreadr5)
cmbhostel.ValueMember = "hostel_id" 
'asign value & display member b4 datasource to avoid errors
cmbhostel.DisplayMember = "hostel_name"
cmbhostel.DataSource = dt5

有一些类似的问题:ComboBox has its old value after Clear();但是,他们没有解决我的问题。

1 个答案:

答案 0 :(得分:1)

改变这就行了:

Dim b As New BindingSource()
b.DataSource = dat
cmbstud.DataSource = b
b.ResetBindings(False)