0

我有一个中继器,它在每次迭代中从多个表中获取数据。现在我一进入 OnItemDataBound 事件就打开连接并在事件完成之前关闭它。这意味着在我的情况下,连接打开和关闭超过 1000 次。这是正确的方法吗?还有其他方法吗?

我的代码基本上是这样的

 Protected Sub myRepeater_OnItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
    Try
        mycon.open()
        Dim RowView As DataRowView = e.Item.DataItem

        //fetch data from 5 different tables using the data from the datasource (dataset)

        mycon.close()
    Catch ex As Exception

    End Try
End Sub
4

1 回答 1

1

实际上,在尽可能小的范围内立即打开/关闭连接是一种很好的做法,因为在使用连接池时不会阻塞物理连接。当您关闭它时,您只是使连接可用。

但除此之外,您为什么要使用在转发器已经数据绑定之后ItemDataBound引发的连接?应该包含您需要的所有内容。如果您想要子控件,例如 DropDownLists 或嵌套中继器,是的,这是正确的方法(那么,您最好将其封装在方法中)。DataItemDataBind

你应该使用using-statementdispose(close) 连接:

Dim rowView As DataRowView = e.Item.DataItem
Dim someDropDown = DirectCast(e.Row.FindControl("DropDownList1"), DropDownList)
Using myCon = New SqlConnection(connectionString)
    Try
        mycon.Open()
        'databind the dropdown...'
    Catch ex As Exception
        'log exception'
    End Try
End Using
于 2012-09-27T21:28:48.217 回答