Monday, January 9, 2012

How To Bind Gridview with SQL Server data


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Management;
using System.Web.Configuration; // this namespace is use to access web.config file. 
using System.Data.SqlClient;  
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionstring = Convert.ToString(WebConfigurationManager.AppSettings["Connection"]);
      //we access the connection string from web.config's app sating  tag 
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand com = new SqlCommand("select * from a", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
}

web.config file  as 


<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
<appSettings>
<add key="Connection" value="server=MUKHERJE-52893C;Initial Catalog=Data; Integrated Security=true"/>
</appSettings>
</configuration>



No comments:

SQL Optimization

  SQL Optimization  1. Add where on your query  2. If you remove some data after the data return then remove the remove condition in the sel...