FAQ in Data Presentation Controls

Rate It (2)

Last post 11-25-2008 12:59 AM by Allen Chen – MSFT. 0 replies.

Sort Posts:

  • FAQ in Data Presentation Controls

    11-25-2008, 12:59 AM
    Locked
    1.   GridView Control

    1.1   Sorting and paging in the GridView control when not using data source controls

    1.2   How to display an empty GridView control

    1.3   Size of GridView overflows

    1.4   Using CheckBox controls in the GridView control

    1.5   Building a custom page template

    1.6   How to access page number buttons and change their styles

    1.7   How to export GridView to an Excel file

    1.8   How to send GridView data in an e-mail message

    2.   DataList Control   

    2.1   Display data horizontally

    2.2   Paging in the DataList control

    3.   DetailsView Control  

    3.1   Master/details scenario

    4.   Common Problems

    4.1   How to dynamically create columns in a data presentation control

    4.2   Connection String Settings

    4.3   How to display columns in GridView or DataGrid controls by using a fixed width

    4.4   When to use GridView/DataGrid/DataList/Repeater controls

    4.5   How do I get data out of the Data Controls?

     

    1. GridView Control


    1.1 Sorting and paging in the GridView control when not using data source controls [Top]

    Sometimes you want to bind the GridView control to data without using a data source control such as the SqlDataSource or ObjectDataSource control. This means that sorting and paging will not be handled automatically by the data source control. In order to implement sorting and paging, you must handle the PageIndexChanging and Sorting events of the GridView control, as shown in the following example:
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.DataSource = SortDataTable(GetYourDataSource(), true);
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }
       
    private string GridViewSortDirection
    {
        get { return ViewState["SortDirection"] as string ?? "ASC"; }
        set { ViewState["SortDirection"] = value; }
    }
    
    private string GridViewSortExpression
    {
        get { return ViewState["SortExpression"] as string ?? string.Empty; }
        set { ViewState["SortExpression"] = value; }
    }
    
    private string ToggleSortDirection()
    {
        switch (GridViewSortDirection)
        {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;
            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }
        return GridViewSortDirection;
    }
    
    protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
    {
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            if (GridViewSortExpression != string.Empty)
            {
                if (isPageIndexChanging)
                {
                    dataView.Sort = string.Format("{0} {1}", 
    GridViewSortExpression,GridViewSortDirection); } else { dataView.Sort = string.Format("{0} {1}",
    GridViewSortExpression,ToggleSortDirection()); } } return dataView; } else { return new DataView(); } } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { GridViewSortExpression = e.SortExpression; int pageIndex = GridView1.PageIndex; GridView1.DataSource = SortDataTable(GetYourDataSource(), false); GridView1.DataBind(); GridView1.PageIndex = pageIndex; }


    Related posts:

    Dynamically sort in the GridView control

    How to sort and page in the GridView control


     

    1.2 How to display an empty GridView control [Top]

    When there is no data for the GridView control to display, by default the control is not rendered. If you want to show headers even if there is no data, you can create a temporary DataTable object that contains an empty record and then bind the GridView control to the data table in the page's Init event. The following example shows how to do this.

    protected void GridView1_Init(Object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Column1");
        dt.Columns.Add("Column2");
        DataRow dr = dt.NewRow();
        dr["Column1"] = "";
        dr["Column2"] = "";
        dt.Rows.Add(dr);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    Another solution is to inherit from GridView and override the CreateChildControls method. This approach can automatically use existing column layout, and it removes the need to use an extra DataTable object. The following example shows how to do this.
    public class EmptyGridView : GridView
    {
        #region Properties
        /// <summary>
        /// Enable or Disable generating an empty table if no data rows in source
        /// </summary>
        [
        Description("Enable or disable generating an empty table with headers 
             when no data rows are available in the data source."),
        Category("Misc"),
        DefaultValue("true"),
        ]
        public bool ShowEmptyTable
        {
            get
            {
                object o = ViewState["ShowEmptyTable"];
                return (o != null ? (bool)o : true);
            }
            set
            {
                ViewState["ShowEmptyTable"] = value;
            }
        }
        /// <summary>
        /// Get or Set Text to display in empty data row
        /// </summary>
        [
        Description("Text to display in the empty data row."),
        Category("Misc"),
        DefaultValue(""),
        ]
        public string EmptyTableRowText
        {
            get
            {
                object o = ViewState["EmptyTableRowText"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["EmptyTableRowText"] = value;
            }
        }
        #endregion
        protected override int CreateChildControls(System.Collections.IEnumerable 
                dataSource, bool dataBinding)
        {
            int numRows = base.CreateChildControls(dataSource, dataBinding);
            // No data rows created, so create an empty table if enabled.
            if (numRows == 0 && ShowEmptyTable)
            {
                //create table
                Table table = new Table();
                table.ID = this.ID;
                //create a new header row
                GridViewRow row = base.CreateRow(-1, -1, DataControlRowType.Header, 
                    DataControlRowState.Normal);
                //convert the exisiting columns into an array and initialize
                DataControlField[] fields = new 
                    DataControlField[this.Columns.Count];
                this.Columns.CopyTo(fields, 0);
                this.InitializeRow(row, fields);
                table.Rows.Add(row);
                //create the empty row
                row = new GridViewRow(-1, -1, DataControlRowType.DataRow,
                   DataControlRowState.Normal);
                TableCell cell = new TableCell();
                cell.ColumnSpan = this.Columns.Count;
                cell.Width = Unit.Percentage(100);
                cell.Controls.Add(new LiteralControl(EmptyTableRowText));
                row.Cells.Add(cell);
                table.Rows.Add(row);
                this.Controls.Add(table);
            }
            return numRows;
        }
    }
      
    Related posts:

    How to display a Gridview header and footer when the SqlDataSource control returns no data


     

    1.3 Size of GridView overflows [Top]

    If the GridView control attempts to display more columns or rows than there is space available in the page, this can cause the GridView control to overflow and alter the appearance of the whole page. You can resolve this by adding a horizontal or vertical scroll bar to the control, as shown in the following example:

    <div style="vertical-align:top; height:200px; width:100%; overflow:auto;">


    Related posts:

    Need a scrollbar in the GridView control


     

    1.4 Using CheckBox controls in the GridView control [Top]

    In Web-based e-mail clients such as Hotmail or Yahoo, a column contains check boxes that can be used to select individual e-mail messages. Currently the GridView control does not have built-in support for this, but you can implement this yourself.

    For an example of how to extend the GridView control to implement check boxes, see the forum posting at http://msdn.microsoft.com/en-us/magazine/cc163612.aspx.

     

    Related posts

    How to add a CheckBox in the GridView control

    How to select all rows from all pages in a GridView control

    Accessing CheckBox controls in the in GridView control


     

    1.5 Building a custom page template [Top]

    To show information such as a total page count in the pager area, you can use the <PagerTemplate> element, as shown in the following example:
    <asp:GridView ID="GridView1" runat="server" 
        DataSourceID="SqlDataSource1" 
        DataKeyNames="ID" 
        AllowPaging="true" 
        PageSize="10" 
        AutoGenerateColumns="true">
      <PagerTemplate>
        <asp:Label ID="LabelCurrentPage" runat="server" 
            Text="<%# ((GridView)Container.NamingContainer).PageIndex + 1 %>">
        </asp:Label>/
        <asp:Label ID="LabelPageCount" runat="server" 
           Text="<%# ((GridView)Container.NamingContainer).PageCount %>">
        </asp:Label>  
        <asp:LinkButton ID="LinkButtonFirstPage" runat="server" 
            CommandArgument="First" 
            CommandName="Page" 
            enabled="<%# ((GridView)Container.NamingContainer).PageIndex != 0 
                 %>"><<
        asp:LinkButton ID="LinkButtonPreviousPage" runat="server" 
            CommandArgument="Prev" CommandName="Page" 
            enabled="<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>"><
        </asp:LinkButton>
        <asp:LinkButton ID="LinkButtonNextPage" runat="server" 
            CommandArgument="Next" 
            CommandName="Page" 
            enabled="<%# ((GridView)Container.NamingContainer).PageIndex != 
                ((GridView)Container.NamingContainer).PageCount - 1 %>">>
        </asp:LinkButton>
        <asp:LinkButton ID="LinkButtonLastPage" runat="server" 
            CommandArgument="Last" 
            CommandName="Page" 
            enabled="<%# ((GridView)Container.NamingContainer).PageIndex !=
             ((GridView)Container.NamingContainer).PageCount - 1 %>">>>
        </asp:LinkButton> 
      </PagerTemplate>
    </asp:GridView>
     

    1.6 How to access page number buttons and change their styles [Top]

    To customize the selected page number to have a bigger font or a different color, handle the RowDataBound event of the GridView control and apply formatting programmatically. The following example shows how to do this.
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)   
    {   
        if (e.Row.RowType == DataControlRowType.Pager)   
        {   
            TableRow row = e.Row.Controls[0].Controls[0].Controls[0] as TableRow;
            foreach (TableCell cell in row.Cells)   
            {   
                Control lb = cell.Controls[0] ;   
                if (lb is Label)   
                {                               
                    ((Label)lb).ForeColor = System.Drawing.Color.Red;   
                    ((Label)lb).Font.Size = new FontUnit("40px"); 
                }   
                else if (lb is LinkButton)   
                {                        
                     //Here is for changing the rest LinkButton page number.
                }   
            }
        }   
    }
     

    1.7 How to export GridView to an Excel file [Top]

    To export GridView data to an Excel file, follow these steps:

    1. In the page that contains the GridView control, override the VerifyRenderingInServerForm method. This lets you programmatically render the GridView control without rendering the complete page. The default implementation of this method prevents you from rendering the GridView control separately. 
    2. Make sure that the GridView control is inside a form element that contains the attribute runat="server".
    The following example shows the code that is required in order to render the GridView control as an Excel spreadsheet.
    protected void Button1_Click(object sender, System.EventArgs e) 
    { 
        // Clear the response. 
        Response.Clear(); 
        // Set the type and file.name. 
        Response.AddHeader("content-disposition", 
            "attachment;filename=FileName.xls"); 
        Response.Charset = ""; 
        Response.ContentType = "application/vnd.xls"; 
        // Add the HTML from the GridView control to a StringWriter instance so you 
        //   can write it out later.
        System.IO.StringWriter sw = new System.IO.StringWriter(); 
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw); 
        GridView1.RenderControl(hw); 
        // Write the data. 
        Response.Write(sw.ToString); 
        Response.End(); 
    } 
    public override void VerifyRenderingInServerForm(Control control) 
    { 
    }

     

    Related posts:

    Export to Excel


     

    1.8 How to send GridView data in an e-mail message [Top]

    You can send data that is displayed in a GridView control as part of an e-mail message. The technique is similar to how you export GridView data to an Excel file—you get the rendered markup from the GridView control and then add it to an e-mail message. Make sure that the e-mail message is in HTML format.  The following example shows how to do this. (The example assumes that the application is already configured to send e-mail.)
    using System.IO;
    using System.Text;
    using System.Net.Mail;
    private string GridViewToHtml(GridView gv)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        return sb.ToString();
    }
    protected void SendMailButton_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.Body = GridViewToHtml(GridView1);
        mail.IsBodyHtml = true;
        // ...    
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
     

     

    2. DataList Control

    2.1 Display data horizontally [Top]

    The GridView control displays data row by row, which means the layout is vertical. To render data in another layout, the DataList control is a good choice. For example, it can show data horizontally by setting RepeatDirection="Horizontal". You can also use the RepeatColumns property to control how many columns can be shown in each line. 

     

    2.2 Paging in the DataList control [Top]

    Unlike the GridView control, the DataList control does not have automatic paging support. To support paging, you must add code, as shown in the following example:

    int PageSize, RecordCount, PageCount, CurrentPage;
    SqlConnection MyConn;
    public int IndexOfPage
    {
        get { return (int)ViewState["_IndexOfPage"]; }
        set { ViewState["_IndexOfPage "] = value; }
    }
    public int CountOfPage
    {
        get { return (int)ViewState["_CountOfPage"]; }
        set { ViewState["_CountOfPage"] = value; }
    }
    public void Page_Load(Object src, EventArgs e)
    {
        PageSize = 3;
        string MyConnString = 
         @"Server=(local)\SQLEXPRESS;Integrated Security=SSPI;Database=test;Persist Security Info=True";
        MyConn = new SqlConnection(MyConnString);
        MyConn.Open();
        if (!Page.IsPostBack)
        {
            ListBind();
            CurrentPage = 0;
            IndexOfPage = 0;
            RecordCount = CalculateRecord();
            lblRecordCount.Text = RecordCount.ToString();
            PageCount = RecordCount / PageSize;
            lblPageCount.Text = PageCount.ToString();
            CountOfPage = PageCount;
        }
    }  
    public int CalculateRecord()
    {
        int intCount;
        string strCount = "select count(*) as co from student";
        SqlCommand MyComm = new SqlCommand(strCount, MyConn);
        SqlDataReader dr = MyComm.ExecuteReader();
        if (dr.Read())
        {
            intCount = Int32.Parse(dr["co"].ToString());
        }
        else
        {
            intCount = 0;
        }
        dr.Close();
        return intCount;
    }
    ICollection CreateSource()
    {
        int StartIndex;
        StartIndex = CurrentPage * PageSize;
        string strSel = "select * from student";
        DataSet ds = new DataSet();
        SqlDataAdapter MyAdapter = new SqlDataAdapter(strSel, MyConn);
        MyAdapter.Fill(ds, StartIndex, PageSize, "Score");
        return ds.Tables["Score"].DefaultView;
    }
    public void ListBind()
    {
        DataList1.DataSource = CreateSource();
        DataList1.DataBind();
        lbnNextPage.Enabled = true;
        lbnPrevPage.Enabled = true;
        if (CurrentPage == (PageCount - 1)) lbnNextPage.Enabled = false;
        if (CurrentPage == 0) lbnPrevPage.Enabled = false;
        lblCurrentPage.Text = (CurrentPage + 1).ToString();
    }
    public void Page_OnClick(Object sender, CommandEventArgs e)
    {
        CurrentPage = (int)IndexOfPage;
        PageCount = (int)CountOfPage;
        string cmd = e.CommandName;
        switch (cmd)
        {
            case "next":
                if (CurrentPage < (PageCount - 1)) CurrentPage++;
                break;
            case "prev":
                if (CurrentPage > 0) CurrentPage--;
                break;
        }
        IndexPage = CurrentPage;
        ListBind();
    }


    Related posts:

    DataList Paging

     

     

    3. DetailsView Control

    3.1 Master/details scenario [Top]

    If you want to show all records in a GridView control, but want to be able to display one record in detail, you must use a second presentation control. One way is to add a Select button column in the GridView control that displays the select data record; you often use a DetailsView control for this. For more information, see Master-Details on the ASP.NET Web site.

     

     

     

    4. Common Problems

    4.1 How to dynamically create columns in a data presentation control [Top]

    When you do not know how many columns you should add into a GridView control, you can create columns dynamically by using a custom template control, as shown in the following example:

    protected void Page_Load(object sender, EventArgs e)
    {
            if (!IsPostBack)
            {
                TemplateField customField1 = new TemplateField();
                customField1.ShowHeader = true;
                customField1.HeaderTemplate = 
                    new GridViewTemplate(DataControlRowType.Header, "ID", "");
                customField1.ItemTemplate = 
                    new GridViewTemplate(DataControlRowType.DataRow, "", "Contract");
                GridView1.Columns.Add(customField1); 
                GridView1.DataSource = GetDataSource();
                GridView1.DataBind();
            }
    }
    
    public class GridViewTemplate : ITemplate
    {
        private DataControlRowType templateType;
        private string columnName;
        private string columnNameBinding;
        public GridViewTemplate(DataControlRowType type, string colname, 
            string colNameBinding)
        {
            templateType = type;
            columnName = colname;
            columnNameBinding = colNameBinding;
        }
        public void InstantiateIn( System.Web.UI.Control container )
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    Literal lc = new Literal();
                    lc.Text = columnName;          
                    container.Controls.Add(lc);          
                    break;
                case DataControlRowType.DataRow:
                    CheckBox cb = new CheckBox();
                    cb.ID = "cb1";
                    cb.DataBinding += new EventHandler(this.cb_OnDataBinding);  
                    container.Controls.Add(cb);
                    break;
                default:
                    break;
            }
        }
        public void cb_OnDataBinding(object sender, EventArgs e)
       {
            CheckBox cb = (CheckBox)sender;
            GridViewRow container = (GridViewRow)cb.NamingContainer;
            cb.Checked = Convert.ToBoolean(
                ((DataRowView)container.DataItem)[columnNameBinding].ToString());
        }
    }

     

    Related posts:

    Articles on custom GridView fields

    How to create a dynamic GridView control


     

    4.2 Connection String Settings [Top]

    You can configure connection strings in the Web.config file or in code. For more information see Connection Strings Configuration on the ASP.NET Web site.

     

    Related post:

    Connection string in the Web.config file

    Connection string problem


     

    4.3 How to display columns in GridView or DataGrid controls by using a fixed width [Top]

    By default, columns in the GridView and DataGrid controls are automatically sized according to their contents. To specify a fixed width for columns, set the Width property of each TableCell object and set the Wrap property to false. The following example shows how to do this by using the DataGrid control.
    _4.3
    protected void DataGrid1_ItemCreated(object sender, DataGridItemEventArgs e)
    {
        ListItemType lit = e.Item.ItemType;
        if (lit == ListItemType.Header)
        {
            for (int i = 0; i < e.Item.Cells.Count; i++)
            {
                e.Item.Cells[i].Width = Unit.Pixel(50);
                e.Item.Cells[i].Wrap = false;
            }
        }
    }

     

    4.4 When to use GridView/DataGrid/DataList/Repeater controls [Top]

    For information about which data presentation control to use, see Deciding when to use the DataGrid, DataList, or Repeater on the MSDN Web site.

    4.5     How do I get data out of the Data Controls? [Top]

    There're several ways to get data out of Data Controls such as using Control.FindControl() method.

    You can refer to the following post for more details.

    http://forums.asp.net/t/1362718.aspx

     

    Sincerely,
    Allen Chen
    Microsoft Online Community Support

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Page 1 of 1 (1 items)