Click here to Skip to main content
15,898,769 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=studinfo;Integrated Security=True"))
       {
          
           // Create new DataAdapter
           using (SqlDataAdapter a = new SqlDataAdapter(
               "SELECT * FROM Stud_Info", c))
           {
              
               DataTable t = new DataTable();
               a.Fill(t);

              
               GridView1.DataSource = t; // <-- From your designer
               GridView1.DataBind(); }}



the above code work very well also it bind data to gridview

Question : who will manage opening & closing the connection here
Posted
Updated 15-Feb-14 22:19pm
v2
Comments
It automatically does. Please check my answer. :)

Refer - DbDataAdapter.Fill Method (DataTable)[^].
Quote:
The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
 
Share this answer
 
SqlConnection object itself takes care of it. You don't have to explicitly mange this connection every time, i.e Once you provide the Connenction String of your database to the code, connection job is done here.
Now you have to take care of your data by query or procedure and stuff and how you display to the user, i.e In Grid or in listview etc.
And if you might have noticed, you can't inherit this SqlConncetion class.
See the documentation[^]
So as you can see, it takes care itself. :)

-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900