我似乎无法让它发挥作用。我想用相同的数据填充多个下拉列表。每次运行相同的查询效率很低。这是我到目前为止所取得的成就:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then
Dim ddlArray = {lst1, lst2, lst3, lst4, lst5, lst6, lst7, lst8, lst9, lst10}
PopulateObjectList(ddlArray)
End If
End Sub
Sub PopulateObjectList(ByVal ddlArray As Array)
strSQL = "select distinct Object_ID, Object_Description from object"
objCmd = New SqlCommand(strSQL, Master.DBConnect())
For Each ddl In ddlArray
ddl.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
ddl.DataValueField = "Object_ID"
ddl.DataTextField = "Object_Description"
ddl.DataBind()
ddl.Items.Insert(0, "Select Object")
Next
Call Master.DBDisconnect()
End Sub
这当然会给出错误:
ExecuteReader requires an open and available Connection. The connection's current state is closed.
因为在分配初始数据源后关闭了连接。我想我可以改为创建一个变量来保存数据,然后将其绑定到每个下拉列表,但数据集不起作用,我不确定如何做到这一点。
如何使用相同的数据填充十个下拉列表中的每一个,而无需在数据库上运行十个单独的查询?
答案 0 :(得分:1)
CommandBehavior.CloseConnection
首次使用后即关闭连接。相反,读取数据一次,将其复制到对象列表并绑定到该列表。
我想知道为什么DataSet
不起作用。
Sub PopulateObjectList(ByVal ddlArray As Array)
strSQL = "select distinct Object_ID, Object_Description from object"
sqlCon = Master.DbConnect()
da = New SqlDataAdapter(strSQL, sqlCon)
ds = New DataSet
da.Fill(ds)
For Each ddl In ddlArray
ddl.DataSource = ds
ddl.DataValueField = "Object_ID"
ddl.DataTextField = "Object_Description"
ddl.DataBind()
ddl.Items.Insert(0, "Select Object")
Next
Call Master.DBDisconnect()
End Sub