Member_2_1242703
asked on
Binding a GridView in ASP.NET(VB) using Using statements
I'm trying to bind a GridView the proper way. Here's what I'm doing now:
This works, but obviously is not correct. Does anyone have an example of binding a GridView using Using statements?
Using connGV As New SqlConnection(con)
Using cmdGV As New SqlCommand(strQuery, connGV)
Try
Dim ds As New Data.DataSet
Dim da As New Data.SqlClient.SqlDataAdapter(strQuery, con)
da.Fill(ds, "results")
gv.DataSource = ds.Tables("results")
gv.DataBind()
Finally
cmdGV.Connection.Close()
cmdGV.Connection.Dispose()
End Try
End Using
End Using
This works, but obviously is not correct. Does anyone have an example of binding a GridView using Using statements?
Hi Mike;
The using statements will close and dispose of the connGV as well as the cmdGV once the executing code leaves the using blocks so no need to explicitly close and dispose of them. The other thing is that you are not tracking exceptions so no need to use the Try/Finally statement.
The using statements will close and dispose of the connGV as well as the cmdGV once the executing code leaves the using blocks so no need to explicitly close and dispose of them. The other thing is that you are not tracking exceptions so no need to use the Try/Finally statement.
Using connGV As New SqlConnection(con)
Using cmdGV As New SqlCommand(strQuery, connGV)
Dim ds As New Data.DataSet
Dim da As New Data.SqlClient.SqlDataAdapter(strQuery, con)
da.Fill(ds, "results")
gv.DataSource = ds.Tables("results")
gv.DataBind()
End Using
End Using
ASKER
Ok, I guess what was throwing me off was the presence of the query twice. I'm the code below, I've replaced the variable with a query to make it easier to see...
I don't mind having the query in there twice, just curious as to what purpose that serves. I've added the finally statements. Is this part right? Main focus here is to make sure I don't have any open connections once the data is loaded.
Using connGV As New SqlConnection(con)
Using cmdGV As New SqlCommand("SELECT * FROM MYTABLE", connGV)
Try
Dim ds As New Data.DataSet
Dim da As New Data.SqlClient.SqlDataAdapter("SELECT * FROM MYTABLE", con)
da.Fill(ds, "results")
gv.DataSource = ds.Tables("results")
gv.DataBind()
Finally
cmdGV.Connection.Close()
cmdGV.Connection.Dispose()
End Try
End Using
End Using
I don't mind having the query in there twice, just curious as to what purpose that serves. I've added the finally statements. Is this part right? Main focus here is to make sure I don't have any open connections once the data is loaded.
How about this change
Are you having multiple connections?
Dim da As New Data.SqlClient.SqlDataAdapter(cmdGV , con)
Are you having multiple connections?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Perfect. Thank you!!
Open in new window
using statement will take care of that