Dynamically create a DataGrid Control in the background

Source: Internet
Author: User
Create a DataGrid using code, four bind columns, and one template column. The sorting function is supported.

  CreateDataGrid. aspx <% @ Page language = "C #" EnableViewState = "false" Codebehind = "CreateDataGrid. aspx. cs" Inherits = "Csover. myDataGrid" %>
<Script runat = "server">
Public void Page_Load (object sender, EventArgs e)
{
  CreateDataGridForm. Controls. Add (MakeGrid ());
}
</Script>
<! Doctype html public "-// W3C // dtd html 4.0 Transtional // EN">
<Html>
  <Head>
    <Title> Create a DataGrid using code </title>
    <Meta name = "GENERATOR" Content = "Microsoft Visual Studio 7.0">
    <Meta name = "CODE_LANGUAGE" Content = "C #">
    <Meta name = "vs_defaultClientScript" content = "Javascript">
    <Meta name = "vs_targetSchema" content = "http://schemas.microsoft.com/intellisense/ie5">
  </Head>
  <Body MS_POSITIONING = "GridLayout">
    <Form id = "CreateDataGridForm" method = "post" runat = "server">
        <Div align = "center"> <B> Create a DataGrid using code </B> </div>
    </Form>
  </Body>
</Html>  CreateDataGrid. aspx. csusing System;
Using System. Configuration;
Using System. Data;
Using System. Data. SqlClient;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. HtmlControls;
Using System. Drawing;
/// <Summary>
/// Summary of CreateDataGrid
/// </Summary>
Namespace Csover
{
  Public class myDataGrid: Page
  {
      Public String SQL = "Select FirstName, LastName, HomePhone, Title from Employees ";
      Public DataGrid mygrid = new DataGrid ();
      Public String SoreExpression;
 
      /// <Summary>
      /// Create a template column and a column Template
      /// </Summary>
      Public TemplateColumn tm = new TemplateColumn ();
      Public ColumnTemplate mycol = new ColumnTemplate ();       
      Public DataView CreateDataSource ()
      {
            String strSql;
            StrSql = "Data Source =.; Initial Catalog = Northwind; User Id = sa; Password = ;";
            SqlConnection conn = new SqlConnection (strSql );
            SqlDataAdapter db_sqladaptor = new SqlDataAdapter (SQL, conn );
            DataSet ds = new DataSet ();
            Db_sqladaptor.Fill (ds, "Employees ");
            DataView myView = ds. Tables ["Employees"]. DefaultView;
            // MyView. Sort = SortExpression;
            // Response. Write (SQL );
            Return myView;
        }        /// <Summary>
        /// Sort
        /// </Summary>
        /// <Param name = "sender"> </param>
        /// <Param name = "e"> </param>
        Public void Sort_Grid (object sender, DataGridSortCommandEvent Args e)
        {
            SortExpression = e. SortExpression. ToString ();
            Session ["SortField"] = SortExpression. Trim ();
            If (Session ["Order"] = null) Session ["Order"] = "ASC ";
            Session ["Order"] = (Session ["Order"]. ToString () = "DESC ")? "ASC": "DESC ";
            If (Session ["SortField"] = null) Session ["SortField"] = "FirstName ";
            SQL + = "ORDER BY" + Session ["SortField"]. ToString () + "" + Session ["Order"]. ToString ();
            Mygrid. DataSource = CreateDataSource ();
            Mygrid. DataBind ();
        }
        /// <Summary>
        /// Create and set the DataGrid attribute. The attribute here is set to a fixed value. You can also set it dynamically.
        /// </Summary>
        /// <Returns> </returns>
        Public DataGrid MakeGrid ()
        {
            Mygrid. CellPadding = 2;
            Mygrid. Attributes. Add ("align", "center ");
            Mygrid. CellSpacing = 0;
            Mygrid. Width = 500;
            Mygrid. Borderwidth = 1;
            Mygrid. BorderColor = ColorTranslator. FromHtml ("Black ");
            Mygrid. AutoGenerateColumns = false;
            Mygrid. ForeColor = ColorTranslator. FromHtml ("Black ");
            Mygrid. Font. Size = 9;
            Mygrid. Font. Name = "";
            Mygrid. AllowSorting = true;
       
            /// Event processor of the Sort command
            Mygrid. SortCommand + = new DataGridSortCommandEvent Handler (Sort_Grid );            /// Set headerstyle
            Mygrid. HeaderStyle. BackColor = ColorTranslator. FromHtml ("Gold ");
            Mygrid. HeaderStyle. ForeColor = ColorTranslator. FromHtml ("Black ");
            Mygrid. HeaderStyle. Font. Name = "";
            Mygrid. HeaderStyle. Font. Size = 9;
            Mygrid. HeaderStyle. Font. Bold = true;
            Mygrid. HeaderStyle. HorizontalAlign = HorizontalAlign. Center;            // Set alternating Style
            Mygrid. AlternatingItemStyle. BackColor = ColorTranslator. FromHtml ("Silver ");
            Mygrid. AlternatingItemStyle. ForeColor = ColorTranslator. FromHtml ("Black ");            /// Set itemstyle
            Mygrid. ItemStyle. HorizontalAlign = HorizontalAlign. Left;            /// Create binding columns and attributes
            BoundColumn FirstName = new BoundColumn ();
            BoundColumn LastName = newn BoundColumn ();
            BoundColumn HomePhone = nenw BoundColumn ();
            BoundColumn Title = new BoundColumn ();            FirstName. HeaderText = "name ";
            FirstName. DataField = "FirstName ";
            FirstName. SortExpression = "FirstName ";
         
            LastName. HeaderText = "last name ";
            LastName. DataField = "LastName ";
            LastName. SortExpression = "LastName ";
         
            HomePhone. HeaderText = "phone ";
            HomePhone. DataField = "HomePhone ";
            HomePhone. SortExpression = "HomePhone ";            Title. HeaderText = "Title ";
            Title. DataField = "Title ";
            Title. SortExpression = "Title ";
 
            Mygrid. Columns. AddAt (0, FirstName );
            Mygrid. Columns. AddAt (1, LastName );
            Mygrid. Columns. AddAt (2, HomePhone );
            Mygrid. Columns. AddAt (3, Title );
 
            /// Set the attributes of the template column and the ItemStyle Template
            Tm. HeaderText = "** delete information **";
            Tm. HeaderStyle. HorizontalAlign = HorizontalAlign. Center;
            Tm. ItemStyle. BackColor = ColorTranslator. FromHtml ("# fff778 ");
            Tm. ItemStyle. HorizontalAlign = HorizontalAlign. Center;
 
            /// The column template inherits from ITemplate
            Tm. ItemTemplate = mycol;
            Mygrid. Columns. AddAt (4, tm );            /// Bind and return
            Mygrid. DataSource = CreateDataSource ();
            Mygrid. DataBind ();
            Return mygrid;
      }
  }  /// ColumnTemplate inherited from ITemplate
  /// "InstantiateIn" defines who the child control belongs
  Public class ColumnTemplate: ITemplate
  {
      Public void InstantialeIn (Control container)
      {
          Label myLabel = new Label ();
          MyLabel. Text = "click to delete ";
          CheckBox mycheckbox = new CheckBox ();
          Container. Controls. Add (myLabel );
          Container. Controls. Add (mycheckbox );
      }
    }
  }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.