Sunday 20 April 2014

Bind (display) data in gridview using ADO.net conneted achitechture



WAP to display data in ASP.Net GridView Control from SQL  Database using ADO.Net connected Architecture.

Explanation:- for this program, first  you have create a sql server database table ( "EmployeeDetails" ) with few Data fields like EmpID, EmName etc ,And then  create a connection string in web.config file with "testconstr" name, using  following code.
but make sure the Data Source path and AttachDbFilename  path is right or not because in following code I am using my database path.

<connectionStrings>
     <add name="testconstr" connectionString="Data Source=.\SQLEXPRESS; AttachDbFilename=C:\Users\MAKANSINGH\Documents\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

And then open a web page and drop a GridView control  on the webpage from ToolBox ->Data-> Gridview. then write the following code in code behind file and run your program.

If you have any doubt please contact me.

WebForm1.aspx.cs


using System;
using System.Data.SqlClient;
using System.Configuration;

namespace ADO.net_Tutorial
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            string constr = ConfigurationManager.ConnectionStrings["testconstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                SqlCommand cmd = new SqlCommand(" select * from EmployeeDetails", con);
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
            }
        }
    }
}

If anyone have any doubt about the program , please comment and you can also mail me on "ibsarmschauhan13@gmail.com" and "makansingh42@yahoo.com".

Thank you so much :)

No comments:

Post a Comment