dataGrid分组

来源:互联网 发布:沙迪克火花机镜面编程 编辑:程序博客网 时间:2024/06/11 10:45

GridView的分组

public partial class SystemManagement_RoleDetailView : BasePage
{

  private bool _SortedFlag = false;
    private int _SortColumnIndex = -1;
    private string _SortColumnHeader = ""; 

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PopulateGrid("BizDomainDisplayName", SortDirection.Ascending);  

         ResolveGroupingData("BizDomainDisplayName");

  }

    private void ResolveGroupingData(String SortExpression)
    {
        foreach (DataControlField field in grid1.Columns)
        {
            if (field.SortExpression == SortExpression)
            {
                _SortedFlag = true;
                _SortColumnIndex = grid1.Columns.IndexOf(field);
                _SortColumnHeader = field.HeaderText;
                break;
            }

        }
    }

    private void PopulateGrid(string sortfield, SortDirection SortDirection)
    {
        try
        {
            DataView dw = GetData();
            String sortd = String.Empty;
            if (SortDirection == SortDirection.Ascending)
            {
                sortd = "ASC";
            }
            else
            {
                sortd = "DESC";
            }

            if (dw != null)
            {
                dw.Sort = sortfield + " " + sortd;
            }
            grid1.DataSource = dw;
            grid1.DataBind();
            grid1.Columns[0].Visible = false;
            grid1.Columns[1].Visible = false;
            grid1.Columns[2].Visible = false;
        }
        catch(Exception ex)
        {
            LogUtil.Log.Error(this, ex);
        }
    }

 

//关键的一个重写函数
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {

        if (_SortedFlag)
        {

            Table table = (Table)grid1.Controls[0];
            Hashtable htLookUp = new Hashtable();
            foreach (GridViewRow row in grid1.Rows)
            {
                int realIndex = table.Rows.GetRowIndex(row);
                string text = row.Cells[_SortColumnIndex].Text;
                if (!htLookUp.ContainsKey(text))
                {
                    htLookUp.Add(text, null);
                    GridViewRow newHeaderRow = new GridViewRow(realIndex, realIndex, DataControlRowType.DataRow, DataControlRowState.Normal);
                    TableCell newCell = new TableCell();
                    newHeaderRow.Cells.Add(newCell);
                    newCell.ColumnSpan = grid1.Columns.Count;
                    newCell.BackColor = Color.FromArgb(249, 249, 235);
                    newCell.Attributes.Add("ForeColor","#0045A4");
                    newCell.Font.Bold = true;
                    newCell.Text = _SortColumnHeader + " : " + text;
                    table.Controls.AddAt(realIndex, newHeaderRow);
                }
            }

        }
        base.Render(writer);
    }

原创粉丝点击