Thursday, 10 January 2013

Creating A Gridview Programmatically in ASP.NET C#

Creating A Gridview Programmatically in ASP.NET C#



Step 1) Create WebPage .aspx

Step 2)  Include following References
              System.Data;
              System.Data.SqlClient;


Step 3)  Build DataSet using  AdventureWorks Database.
               Here I am using 2 tables 
                1.SalesPerson
                2.Employee

Note  for this exaple you can use any of the Table.

 void BuildDataSet()
        {
        SqlConnection conn = new SqlConnection(@"server=.\sqlexpress2012;
                            database=AdventureWorks2012;
                            trusted_connection=yes;");

        SqlDataAdapter ad = new SqlDataAdapter("select * from
[AdventureWorks2012].[Sales].[SalesPerson] as SalesPerson; "+
        "select * from [AdventureWorks2012].[HumanResources].
[Employee] as Employee",
            conn);

        ad.Fill(ds);
        conn.Close();
       
        }


Step 4)    Programatically Creating a GridView in ASP.NET using C#

void CreateGridView()
{
        GridView view = new GridView();
        view.EmptyDataText = "No data found";
        view.ShowHeaderWhenEmpty = true;
        view.DataSource = ds.Tables[0];
        view.DataBind();
        view.AlternatingRowStyle.BackColor = System.Drawing.Color.Teal;
        view.AlternatingRowStyle.ForeColor = System.Drawing.Color.Wheat;
         form1.Controls.Add(view);
}

Note: Eavery PostBack Dynamic controls needs to be created.

Step 5) Run the Web page.



Tags:Creating A Gridview Programmatically in ASP.NET C#,Dynamically create gridview in asp.net, Dynamic GridView in asp.net, dataBinding to GridView in asp.net,GridView and DataSet Binding,Multiple sql queries to database using ado.net