CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Connecting to SqlServer and Binding a GridView control in ASP.Net
Submitted By Satheesh Babu B
On 10/18/2008 1:07:50 AM
Tags: ADO.Net,CodeDigest,GridView  

Drag a GridView control from the Data tab of Visual studio 2005. Include the namespace "System.Data.SqlClient" for connecting to SqlServer. I have kept the connection string in the Web.Config file.

CodeBehind
protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
{   
DataTable dt = GetUsersForModeration();
gvUsers.DataSource = dt;
 gvUsers.DataBind();
}
}

public DataTable GetUsersForModeration()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con);
        com.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter ada = new SqlDataAdapter(com);
        DataTable ds = new DataTable();
        ada.Fill(dt);
        return dt;
    }

Web.Config:
<connectionStrings>
  <add name="Sql" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;"/>
 </connectionStrings>

Configure your connection string inside the <configuration> tag in your project. Replace the database name to your database. I have used the Sql express database in "app_data" folder in the project.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..