By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,684 Members | 1,439 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to bind a GridView in ASP.net

P: 17
This code will help for the beginners, who want to learn, how to bind a gridview.

Before showing the code I will give a small introduction how to work with gridview.
  1. Add a gridview controls to the ASPX Page.
  2. Create a method to get a data from the database and bind to the gridview
  3. Create a dataset object.
  4. create a sqlcommand object.
  5. create a sqlconnection object


Description:
Below is a sample code.

In ASPX Page
Expand|Select|Wrap|Line Numbers
  1.      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
  2.  
  3.         </asp:GridView>
  4.  
IN ASPX.CS File
Expand|Select|Wrap|Line Numbers
  1.     protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.  
  4.              GetData();
  5.  
  6.         }
  7.     void GetData()
  8.         {
  9.             DataSet ds = new DataSet();
  10.             SqlCommand cmd = new SqlCommand();
  11.             SqlDataAdapter da = new SqlDataAdapter();
  12.             SqlConnection con = new SqlConnection("Data Source=msdb;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=sa");
  13.             if (con.State == ConnectionState.Open)
  14.                 con.Close();
  15.             else
  16.                 con.Open();
  17.             cmd.CommandText = "Select * from Platform";
  18.             cmd.Connection = con;
  19.             da.SelectCommand = cmd;
  20.             da.Fill(ds);
  21.             cmd.ExecuteNonQuery();
  22.             GridView1.DataSource = ds;
  23.             GridView1.DataBind();
  24.         }
  25.  
Summary
There are many topics to learn with ASP.Net. I have covered a small portion hope this will helps all the beginners to startup. Please give your feedback and suggestion.
Mar 23 '11 #1
Share this Article
Share on Google+