Binding data into Gridview from database in asp.net using c#

Now I'm trying to load data into a gridview (binding data into gridview) from database in ASP.Net connect to SQL Server 2008. I have a gridview with three columns , which are boundfields. My database is designed in SQL Server 2008. I want to load data from a table, TblProduct , into a gridview when pageload in ASP.Net. I will load data from this table with three column , ProID , ProName, and MadeIn. Please see example below:

Figure 1: Sample table
Form design :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
   <Columns>
     <asp:BoundField DataField="ProID" HeaderText="Product ID" SortExpression="ProID" />
     <asp:BoundField DataField="ProName" HeaderText="Product Name" SortExpression="ProName" />
     <asp:BoundField DataField="MadeIn" HeaderText="Made In" SortExpression="MadeIn" />
   </Columns>

</asp:GridView>

Code Behind :
//import these two namespaces: System.Data and System.Data.SqlClient  to use  .NET 
//Framework Data Provider for SQL Server
using System.Data;
using System.Data.SqlClient;
//Event page load
   protected void Page_Load(object sender, EventArgs e)
    {

       if (!IsPostBack) {
          DataTable dt = new DataTable();
          //calling function Loadlist
          dt = Loadlist();
                  
                        //Binding data into gridview
          GridView1.DataSource = dt;
          GridView1.DataBind();
       }

    }

    public DataTable Loadlist()
    {
       SqlConnection con = new SqlConnection();
       string str;
       string sql;

       str="Server=UBEE_THAROTH ; Database=Drink;uid=sa;pwd=123;";
       sql = "Select ProID , ProName , MadeIn from TblProduct order by ProID asc";
                
                // connect to database
       con.ConnectionString = str;
       con.Open();
              
                //fill data into datatable
       SqlDataAdapter da = new SqlDataAdapter(sql,con);
       DataTable dt = new DataTable();
       da.Fill(dt);

       if(dt.Rows.Count>0){
           dt.Dispose(); 
           da.Dispose();
           con.Dispose();
           return dt;
       }
       else {
           dt.Dispose(); 
           da.Dispose();
           con.Dispose();
           return null;
       }           
   }

  Done ...hope you fun with it :-) :)
Binding data into Gridview from database in asp.net using c# Binding data into Gridview from database in asp.net using c# Reviewed by BeiLover on 10:50 AM Rating: 5

No comments:

Powered by Blogger.