public static void OutputExcel(Nandasoft.WebControls.NDGridView grid, string excelFileName)
        {
            Page page = (Page)HttpContext.Current.Handler;

            string[] flag = new string[grid.Columns.Count];
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                DataControlField col = grid.Columns[i];

                //只有可见的邦定列和选择列才输出
                if (col.Visible && (col.GetType() == typeof(BoundField) || col.GetType() == typeof(CheckBoxField)))
                {
                    flag[i] = col.HeaderText;
                }
                else
                {
                    flag[i] = "";
                }
            }
            page.Response.Clear();
            string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));

            page.Response.AddHeader("Content-Disposition", "filename=" + fileName + ".xls");
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.Charset     = "utf-8";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");
            sb.Append("<table border=1>");
            sb.Append("<tr><b>");
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                if (flag[i] != "")
                {
                    sb.Append("<td>" + grid.Columns[i].HeaderText + "</td>");
                }
            }
            sb.Append("</b></tr>");


            for (int i = 0; i < grid.Rows.Count; i++)
            {
                if (((CheckBox)grid.Rows[i].Cells[1].FindControl("CheckBoxSelect")).Checked == true)
                {
                    sb.AppendLine("<tr>");
                    for (int j = 0; j < grid.Columns.Count; j++)
                    {
                        if (flag[j] != "")
                        {
                            if (grid.Rows[i].Cells[j].Controls.Count > 0)
                            {
                                if (grid.Rows[i].Cells[j].Controls[0].GetType().ToString().Trim() == "System.Web.UI.WebControls.CheckBox")
                                {
                                    if (((CheckBox)grid.Rows[i].Cells[j].Controls[0]).Checked)
                                    {
                                        sb.Append("<td>是</td>");
                                    }
                                    else
                                    {
                                        sb.Append("<td>否</td>");
                                    }
                                }
                                else
                                {
                                    sb.Append("<td>" + grid.Rows[i].Cells[j].Text + "</td>");
                                }
                            }
                            else
                            {
                                sb.Append("<td>" + grid.Rows[i].Cells[j].Text + "</td>");
                            }
                        }
                    }
                    sb.AppendLine("</tr>");
                }
            }

            sb.Append("</table>");
            sb.Append("</body></html>");

            page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(sb.ToString()));
            page.Response.End();
        }
示例#2
0
 public void DoCopyProperties(DataControlField newField)
 {
     base.CopyProperties(newField);
 }
示例#3
0
 public static bool Lacks(this DataControlFieldCollection collection, DataControlField field)
 {
     return(!collection.Contains(field));
 }
示例#4
0
 protected override void OnInit(EventArgs e)
 {
     base.OnInit(e);
     if (!base.DesignMode)
     {
         int key = 0;
         foreach (DataControlField field in this.Columns)
         {
             string statField = "";
             if (field is WTF.Controls.BoundField)
             {
                 statField = ((WTF.Controls.BoundField)field).StatField;
             }
             else if (field is WTF.Controls.HyperLinkField)
             {
                 statField = ((WTF.Controls.HyperLinkField)field).StatField;
             }
             else if (field is WTF.Controls.TemplateField)
             {
                 statField = ((WTF.Controls.TemplateField)field).StatField;
             }
             if (!string.IsNullOrWhiteSpace(statField))
             {
                 this._StatFieldList.Add(key, statField);
                 this._StatValueList.Add(key, 0.0);
                 this.ShowFooter = true;
             }
             key++;
         }
         if (this.AllowSorting)
         {
             base.Sorting += new GridViewSortEventHandler(this.MyGridView_Sorting);
             if (this.IsAutoSortFields)
             {
                 foreach (DataControlField field in this.Columns)
                 {
                     if (field is WTF.Controls.BoundField)
                     {
                         if (string.IsNullOrEmpty(field.SortExpression) && ((WTF.Controls.BoundField)field).IsAutoSort)
                         {
                             field.SortExpression = ((WTF.Controls.BoundField)field).DataField;
                         }
                     }
                     else if ((field is WTF.Controls.HyperLinkField) && (string.IsNullOrEmpty(field.SortExpression) && ((WTF.Controls.HyperLinkField)field).IsAutoSort))
                     {
                         field.SortExpression = ((WTF.Controls.HyperLinkField)field).DataTextField;
                     }
                 }
             }
         }
         this.PageSize = 500;
         if (this.IsUserPager)
         {
             PagerTemplate template = new PagerTemplate(this);
             template.PagerChangeCommand += new PagerChangeEventHandler(this.On_PagerChangeCommand);
             template.CurrentPageIndex    = this.PageIndex;
             this.PagerTemplate           = template;
         }
         if (this.OperateStyle == WTF.Framework.OperateStyle.RowOperate)
         {
             bool             flag    = false;
             DataControlField field2  = null;
             Operate          operate = new Operate();
             foreach (DataControlField field in this.Columns)
             {
                 if (field is OperateField)
                 {
                     if (((OperateField)field).DataTextField.IsNull())
                     {
                         field2 = field;
                     }
                     operate.Buttons = ((OperateField)field).Buttons;
                     flag            = true;
                 }
             }
             if (field2 != null)
             {
                 this.Columns.Remove(field2);
             }
             if (flag)
             {
                 this.Columns.Add(operate);
             }
         }
     }
 }
        protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
        {
            int rows = base.CreateChildControls(dataSource, dataBinding);

            //  no data rows created, create empty table if enabled
            if (rows == 0 && (this.ShowFooterWhenEmpty || this.ShowHeaderWhenEmpty))
            {
                //  create the table
                Table table = this.CreateChildTable();

                DataControlField[] fields;
                if (this.AutoGenerateColumns)
                {
                    PagedDataSource source = new PagedDataSource();
                    source.DataSource = dataSource;

                    System.Collections.ICollection autoGeneratedColumns = this.CreateColumns(source, true);
                    fields = new DataControlField[autoGeneratedColumns.Count];
                    autoGeneratedColumns.CopyTo(fields, 0);
                }
                else
                {
                    fields = new DataControlField[this.Columns.Count];
                    this.Columns.CopyTo(fields, 0);
                }

                if (this.ShowHeaderWhenEmpty)
                {
                    //  create a new header row
                    GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                    this.InitializeRow(headerRow, fields);

                    //  add the header row to the table
                    table.Rows.Add(headerRow);
                }

                //  create the empty row
                GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                TableCell   cell     = new TableCell();
                cell.ColumnSpan = fields.Length;
                cell.Width      = Unit.Percentage(100);

                //  respect the precedence order if both EmptyDataTemplate
                //  and EmptyDataText are both supplied ...
                if (this.EmptyDataTemplate != null)
                {
                    this.EmptyDataTemplate.InstantiateIn(cell);
                }
                else if (!string.IsNullOrEmpty(this.EmptyDataText))
                {
                    cell.Controls.Add(new LiteralControl(EmptyDataText));
                }

                emptyRow.Cells.Add(cell);
                table.Rows.Add(emptyRow);

                if (this.ShowFooterWhenEmpty)
                {
                    //  create footer row
                    footerRow = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
                    this.InitializeRow(footerRow, fields);

                    //  add the footer to the table
                    table.Rows.Add(footerRow);
                }

                this.Controls.Clear();
                this.Controls.Add(table);
            }

            return(rows);
        }
示例#6
0
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            int rows = base.CreateChildControls(dataSource, dataBinding);

            // no data rows created, create empty table if enabled
            if (rows == 0 && (ShowFooterWhenEmpty || ShowHeaderWhenEmpty))
            {
                // create the table
                Table table = CreateChildTable();

                Controls.Clear();
                Controls.Add(table);

                DataControlField[] fields;
                if (AutoGenerateColumns)
                {
                    var source = new PagedDataSource {
                        DataSource = dataSource
                    };

                    ICollection autoGeneratedColumns = CreateColumns(source, true);
                    fields = new DataControlField[autoGeneratedColumns.Count];
                    autoGeneratedColumns.CopyTo(fields, 0);
                }
                else
                {
                    fields = new DataControlField[Columns.Count];
                    Columns.CopyTo(fields, 0);
                }

                TableRowCollection newRows = table.Rows;
                if (ShowHeaderWhenEmpty)
                {
                    // create a new header row
                    _headerRow = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                    InitializeRow(_headerRow, fields, newRows);
                }

                // create the empty row
                GridViewRow             emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                TableCell               cell     = new TableCell();
                List <DataControlField> f        = fields.Where(dataControlField => dataControlField.Visible).ToList();
                cell.ColumnSpan = f.Count;
                //cell.Width = Unit.Percentage(100);

                // respect the precedence order if both EmptyDataTemplate
                // and EmptyDataText are both supplied ...
                if (EmptyDataTemplate != null)
                {
                    EmptyDataTemplate.InstantiateIn(cell);
                }
                else if (!string.IsNullOrEmpty(EmptyDataText))
                {
                    cell.Controls.Add(new LiteralControl(EmptyDataText));
                }

                emptyRow.Cells.Add(cell);
                GridViewRowEventArgs e = new GridViewRowEventArgs(emptyRow);
                OnRowCreated(e);

                newRows.Add(emptyRow);

                emptyRow.DataBind();
                OnRowDataBound(e);
                emptyRow.DataItem = null;

                if (ShowFooterWhenEmpty && ShowFooter)
                {
                    // create footer row
                    _footerRow = CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
                    InitializeRow(_footerRow, fields, newRows);
                    newRows.Remove(emptyRow);
                }
            }

            return(rows);
        }
示例#7
0
 public GridViewExHeaderCell(GridViewEx gv, DataControlField containingField)
     : base(containingField)
 {
     _gv = gv;
 }
	public bool Contains(DataControlField field) {}
 public ExpandTableCell(HtmlTextWriterTag tagKey, DataControlField containingField) : base(tagKey, containingField)
 {
 }
示例#10
0
 protected override void CopyProperties(DataControlField newField)
 {
     base.CopyProperties(newField);
     ((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
 }
示例#11
0
 public ExpandTableCell(DataControlField containingField) : base(containingField)
 {
 }
	// Constructors
	public DataControlFieldHeaderCell(DataControlField containingField) {}
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "ChiTietCa_ID" + Request.QueryString["IDCaSau"] + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xls";
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.ContentType = "application/vnd.ms-excel";

                string s = @"<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/></head><body style='text-align:center;font-family:Times New Roman;'><br/><br/>";
                s += "<table border='1'>";
                s += "<tr><td colspan='" + grvChiTiet.Columns.Count.ToString() + "'><b>THÔNG TIN HIỆN TẠI</b></td></tr>";
                s += "<tr>";
                DataControlField col = null;
                for (int i = 0; i < grvChiTiet.Columns.Count; i++)
                {
                    col = grvChiTiet.Columns[i];
                    s  += "<td style='background-color:#CCC;'>" + col.HeaderText + "</td>";
                }
                s += "</tr>";
                GridViewRow row = null;
                for (int i = 0; i < grvChiTiet.Rows.Count; i++)
                {
                    row = grvChiTiet.Rows[i];
                    s  += "<tr>";
                    TableCell cell = null;
                    int       j    = 0;
                    for (j = 0; j < row.Cells.Count - 1; j++)
                    {
                        cell = row.Cells[j];
                        s   += "<td>" + cell.Text + "</td>";
                    }
                    Label l = (Label)(row.Cells[j].FindControl("lblStatus"));
                    s += "<td>" + l.Text + "</td>";
                    s += "</tr>";
                }
                s += "</table><br/><br/>";
                //-------------------------------------------------
                s += "<table border='1'>";
                int cols = grvDanhSach.Columns.Count - 4;
                s += "<tr><td colspan='" + cols.ToString() + "'><b>CHI TIẾT BIẾN ĐỘNG</b></td></tr>";
                s += "<tr>";
                for (int i = 0; i < grvDanhSach.Columns.Count - 4; i++)
                {
                    col = grvDanhSach.Columns[i];
                    s  += "<td style='background-color:#CCC;'>" + col.HeaderText + "</td>";
                }
                s += "</tr>";
                for (int i = 0; i < grvDanhSach.Rows.Count; i++)
                {
                    row = grvDanhSach.Rows[i];
                    s  += "<tr>";
                    TableCell cell = null;
                    for (int j = 0; j < row.Cells.Count - 4; j++)
                    {
                        cell = row.Cells[j];
                        if (j == 2)
                        {
                            Label l = (Label)(cell.FindControl("lblOldValue"));
                            s += "<td>" + l.Text + "</td>";
                        }
                        else if (j == 3)
                        {
                            Label l = (Label)(cell.FindControl("lblNote"));
                            s += "<td>" + l.Text + "</td>";
                        }
                        else
                        {
                            s += "<td>" + cell.Text + "</td>";
                        }
                    }
                    s += "</tr>";
                }
                s += "</table><br/><br/>";
                //-------------------------------------------------
                if (grvSinhSan.Rows.Count > 0)
                {
                    s += "<table border='1'>";
                    s += "<tr><td colspan='" + grvSinhSan.Columns.Count.ToString() + "'><b>THỐNG KÊ SINH SẢN</b></td></tr>";
                    s += "<tr>";
                    for (int i = 0; i < grvSinhSan.Columns.Count; i++)
                    {
                        col = grvSinhSan.Columns[i];
                        s  += "<td style='background-color:#CCC;'>" + col.HeaderText + "</td>";
                    }
                    s += "</tr>";
                    for (int i = 0; i < grvSinhSan.Rows.Count; i++)
                    {
                        row = grvSinhSan.Rows[i];
                        s  += "<tr>";
                        TableCell cell = null;
                        for (int j = 0; j < row.Cells.Count; j++)
                        {
                            cell = row.Cells[j];
                            s   += "<td>" + cell.Text + "</td>";
                        }
                        s += "</tr>";
                    }
                    s += "</table>";
                }
                //-------------------------------------------------
                s += "</body></html>";
                Response.Write(s);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
	public int IndexOf(DataControlField field) {}
示例#15
0
 public MetaGridCustomColumnInfo(string Type, string Id, DataControlField Column)
     : this(Type, Id)
 {
     this.Column = Column;
 }
	public void Remove(DataControlField field) {}
示例#17
0
 public ChangingMetaGridColumnHeaderEventArgs(DataControlField controlField, MetaField field)
 {
     _controlField = controlField;
     _field        = field;
 }
	// Constructors
	public DataControlFieldCell(DataControlField containingField) {}
示例#19
0
    public static void SetupMenuGrid(string tablename, GridView grid)
    {
        SortedList <int, Column> columns = new SortedList <int, Column>();
        Table tab = new Table(tablename);

        foreach (Column c in tab.Columns)
        {
            if (c.IsListShow)
            {
                int key = c.ListShowOrder;
                while (columns.ContainsKey(key))
                {
                    key++;
                }
                columns.Add(key, c);
            }
        }
        BoundField field1 = new BoundField();

        field1.DataField       = "depth";
        field1.ItemStyle.Width = new Unit(30);
        grid.Columns.Add(field1);

        foreach (Column c in columns.Values)
        {
            DataControlField field = ListFieldFactory.GetListField(c.ListShowType.ToString(), tablename, c.ColumnName);
            if (c.ColumnName == columns.Values[0].ColumnName)
            {
                field.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                field.ItemStyle.CssClass        = string.Empty;
            }
            grid.Columns.Add(field);
        }

        //添加排序
        if (!string.IsNullOrEmpty(tab.OrderField))
        {
            HyperLinkField orderup = new HyperLinkField();
            orderup.Text = "<img src='images/up.jpg' border=0 />";
            orderup.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            orderup.DataNavigateUrlFormatString = "OrderGO.aspx?id={0}&d=up&t=" + tablename + "&desc=1";
            orderup.ItemStyle.Width             = new Unit(20);
            grid.Columns.Add(orderup);

            HyperLinkField orderdown = new HyperLinkField();
            orderdown.Text = "<img src='images/down.jpg' border=0 />";
            orderdown.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            orderdown.DataNavigateUrlFormatString = "OrderGO.aspx?id={0}&d=down&t=" + tablename + "&desc=1";
            orderdown.ItemStyle.Width             = new Unit(20);
            grid.Columns.Add(orderdown);
        }
        //添加添加
        if (tab.AddChildDepth != 0 && tab.AddChildDepth != 1)
        {
            HyperLinkField addField = new HyperLinkField();
            addField.Text = "添加子栏目";
            addField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            addField.HeaderText                  = "<a href='edit.aspx?id=0&type=add&f=menu&t=" + tablename + "&p=&m='>添加栏目</a>";
            addField.DataNavigateUrlFormatString = "edit.aspx?id={0}&type=add&f=menu&t=" + tablename + "&p=" + HttpContext.Current.Request.QueryString["p"] + "&m=" + HttpContext.Current.Request.QueryString["m"];
            addField.ItemStyle.Width             = new Unit(70);
            grid.Columns.Add(addField);
        }
        //添加编辑
        HyperLinkField editField = new HyperLinkField();

        editField.Text = "编辑";
        editField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
        editField.HeaderText                  = "编辑";
        editField.DataNavigateUrlFormatString = "edit.aspx?id={0}&f=menu&t=" + tablename + "&p=" + HttpContext.Current.Request.QueryString["p"] + "&m=" + HttpContext.Current.Request.QueryString["m"];
        editField.ItemStyle.Width             = new Unit(40);
        grid.Columns.Add(editField);
        //添加删除
        ConfirmLinkField delField = new ConfirmLinkField();

        delField.Text = "删除";
        delField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
        delField.DataNavigateUrlFormatString = "del.aspx?id={0}&t=" + tablename;
        delField.HeaderText      = "删除";
        delField.ItemStyle.Width = new Unit(40);
        grid.Columns.Add(delField);


        DataTable sourceTable = new DataTable();

        sourceTable.Columns.Add("depth");
        SetupMenuSource(tablename, sourceTable, 0, tab.FKField, 0);

        grid.AutoGenerateColumns = false;

        grid.DataSource = sourceTable;
        grid.DataBind();
    }
示例#20
0
        private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
        {
            if (rows.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag(tableSection);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (GridViewRow row in rows)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("tr");

                    string className = GetRowClass(gridView, row);
                    if (!String.IsNullOrEmpty(className))
                    {
                        writer.WriteAttribute("class", className);
                    }
                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    int i = 0;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (!gridView.Columns[i++].Visible)
                        {
                            continue;
                        }

                        DataControlFieldCell fieldCell = cell as DataControlFieldCell;

                        if (tableSection == "tbody" && fieldCell != null &&
                            (fieldCell.Text.Trim() == "") && fieldCell.Controls.Count == 0)
                        {
                            cell.Controls.Add(new LiteralControl("<div style=\"width:1px;height:1px;\">&nbsp;</div>"));
                        }
                        else if (tableSection == "thead" && fieldCell != null &&
                                 !String.IsNullOrEmpty(gridView.SortExpression) &&
                                 fieldCell.ContainingField.SortExpression == gridView.SortExpression)
                        {
                            cell.Attributes["class"] = "AspNet-GridView-Sort";
                        }

                        if ((fieldCell != null) && (fieldCell.ContainingField != null))
                        {
                            DataControlField field = fieldCell.ContainingField;
                            if (!field.Visible)
                            {
                                cell.Visible = false;
                            }

                            if (field.ItemStyle.Width != Unit.Empty)
                            {
                                cell.Style["width"] = field.ItemStyle.Width.ToString();
                            }

                            if (!field.ItemStyle.Wrap)
                            {
                                cell.Style["white-space"] = "nowrap";
                            }

                            if ((field.ItemStyle != null) && (!String.IsNullOrEmpty(field.ItemStyle.CssClass)))
                            {
                                if (!String.IsNullOrEmpty(cell.CssClass))
                                {
                                    cell.CssClass += " ";
                                }
                                cell.CssClass += field.ItemStyle.CssClass;
                            }
                        }

                        writer.WriteLine();
                        cell.RenderControl(writer);
                    }

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("tr");
                }

                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag(tableSection);
            }
        }
示例#21
0
    public static void SetupGrid(string tablename, GridView grid, string searchStr, string treeStr, int pagesize, int nowpage, out int RecCount)
    {
        SortedList <int, Column> columns = new SortedList <int, Column>();
        Table tab = new Table(tablename);

        foreach (Column c in tab.Columns)
        {
            if (c.IsListShow)
            {
                int key = c.ListShowOrder;
                while (columns.ContainsKey(key))
                {
                    key++;
                }
                columns.Add(key, c);
            }
        }
        string sql = "select " + tab.PKFiled;

        foreach (Column c in columns.Values)
        {
            if (sql == "select")
            {
                sql += " " + c.ColumnName;
                if (c.ListShowType == ListShowType.Foreign)
                {
                    string fsql = "(select " + c.DataTextField + " from testnewstype where " + c.DataValueField + "=" + tablename + "." + c.ColumnName + ") as " + c.ColumnName + "_Foreign";
                    sql += "," + fsql;
                }
            }
            else
            {
                sql += "," + c.ColumnName;
                if (c.ListShowType == ListShowType.Foreign)
                {
                    string fsql = "(select " + c.DataTextField + " from " + c.ForeignTable + " where " + c.DataValueField + "=" + tablename + "." + c.ColumnName + ") as " + c.ColumnName + "_Foreign";
                    sql += "," + fsql;
                }
            }
            DataControlField field = ListFieldFactory.GetListField(c.ListShowType.ToString(), tablename, c.ColumnName);
            grid.Columns.Add(field);
        }
        sql += " from " + tab.TableName + " where 1=1";

        if ((!string.IsNullOrEmpty(searchStr)) && (!string.IsNullOrEmpty(tab.SearchColumn)))
        {
            sql += " and (";
            string   searchSql = string.Empty;
            string[] arr       = searchStr.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string str in arr)
            {
                if (!string.IsNullOrEmpty(searchSql))
                {
                    searchSql += " or ";
                }
                searchSql += tab.SearchColumn + " like '%" + searchStr.Replace("'", "''") + "%'";
            }

            sql += searchSql;
            sql += ")";
        }
        if ((!string.IsNullOrEmpty(treeStr)) && (!string.IsNullOrEmpty(tab.TreeColumn)))
        {
            sql += " and " + tab.TreeColumn + "='" + treeStr.Replace("'", "''") + "'";
        }

        //Response.Write(sql);
        //Response.End();
        if (!string.IsNullOrEmpty(tab.SelectOrder))
        {
            if (tab.SelectOrder.Trim().ToLower().StartsWith("order by"))
            {
                sql += " " + tab.SelectOrder;
            }
            else
            {
                sql += " order by " + tab.SelectOrder;
            }
        }

        grid.AutoGenerateColumns = false;

        //添加排序
        if (!string.IsNullOrEmpty(tab.OrderField))
        {
            HyperLinkField orderup = new HyperLinkField();
            orderup.Text = "<img src='images/up.jpg' border=0 />";
            orderup.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            orderup.DataNavigateUrlFormatString = "OrderGO.aspx?id={0}&d=up&t=" + tablename;
            orderup.ItemStyle.Width             = new Unit(20);
            grid.Columns.Add(orderup);

            HyperLinkField orderdown = new HyperLinkField();
            orderdown.Text = "<img src='images/down.jpg' border=0 />";
            orderdown.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            orderdown.DataNavigateUrlFormatString = "OrderGO.aspx?id={0}&d=down&t=" + tablename;
            orderdown.ItemStyle.Width             = new Unit(20);
            grid.Columns.Add(orderdown);
        }
        //添加查看
        if (tab.AllowShow)
        {
            HyperLinkField showField = new HyperLinkField();
            showField.Text = "查看";
            showField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            showField.HeaderText                  = "查看";
            showField.DataNavigateUrlFormatString = "show.aspx?id={0}&t=" + tablename + "&p=" + HttpContext.Current.Request.QueryString["p"] + "&m=" + HttpContext.Current.Request.QueryString["m"];
            showField.ItemStyle.Width             = new Unit(40);
            grid.Columns.Add(showField);
        }
        //添加编辑
        if (tab.AllowEdit)
        {
            HyperLinkField editField = new HyperLinkField();
            editField.Text = "编辑";
            editField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            editField.HeaderText                  = "编辑";
            editField.DataNavigateUrlFormatString = "edit.aspx?id={0}&t=" + tablename + "&p=" + HttpContext.Current.Request.QueryString["p"] + "&m=" + HttpContext.Current.Request.QueryString["m"];
            editField.ItemStyle.Width             = new Unit(40);
            grid.Columns.Add(editField);
        }
        if (tab.AllowDel)
        {
            //添加删除
            ConfirmLinkField delField = new ConfirmLinkField();
            delField.Text = "删除";
            delField.DataNavigateUrlFields       = tab.PKFiled.Split(',');
            delField.DataNavigateUrlFormatString = "del.aspx?id={0}&t=" + tablename;
            delField.HeaderText      = "删除";
            delField.ItemStyle.Width = new Unit(40);
            grid.Columns.Add(delField);
        }
        //绑定

        DataTable tabsource = DBFactory.GetConn().exeTable(sql);

        RecCount = tabsource.Rows.Count;
        if (pagesize > 0)
        {
            grid.DataSource = PagerHelper.GetPagedData(pagesize, nowpage, tabsource.DefaultView);
            grid.DataBind();
        }
        else
        {
            grid.DataSource = tabsource;
            grid.DataBind();
        }
    }
示例#22
0
        private void CreateHeaderRow()
        {
            if (ShowHeaderAllways)
            {
                Table maintable = null;
                if (this.Controls.Count == 0)
                {
                    maintable = new Table();
                    maintable.ApplyStyle(this.ControlStyle);
                    this.Controls.Add(maintable);
                }
                else
                {
                    maintable = this.Controls[0] as Table;
                }

                bool IsCreateHeader = false;

                bool IsCreateEmptyRow = false;

                if (maintable.Rows.Count == 0)
                {
                    IsCreateHeader   = true;
                    IsCreateEmptyRow = true;
                }
                else
                {
                    GridViewRow gvr = maintable.Rows[0] as GridViewRow;
                    if (gvr.RowType == DataControlRowType.EmptyDataRow)
                    {
                        maintable.Rows.Clear();
                        IsCreateHeader   = true;
                        IsCreateEmptyRow = true;
                    }
                    else
                    {
                        IsCreateHeader   = false;
                        IsCreateEmptyRow = false;
                    }
                }

                int ColumnCount = 0;

                if (IsCreateHeader)
                {
                    GridViewRow gvr = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
                    gvr.ApplyStyle(this.HeaderStyle);
                    for (int i = 0; i < this.Columns.Count; i++)
                    {
                        DataControlField column = this.Columns[i];

                        if (column.ShowHeader)
                        {
                            ColumnCount++;

                            DataControlFieldHeaderCell tc = new DataControlFieldHeaderCell(column);
                            tc.ApplyStyle(column.HeaderStyle);
                            column.InitializeCell(tc, DataControlCellType.Header, DataControlRowState.Normal, 0);

                            gvr.Cells.Add(tc);
                        }
                    }
                    maintable.Rows.AddAt(0, gvr);
                }

                if (IsCreateEmptyRow)
                {
                    if (this.EmptyDataText != string.Empty)
                    {
                        GridViewRow gvr = new GridViewRow(0, 0, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                        gvr.ApplyStyle(this.EmptyDataRowStyle);
                        TableCell tc = new TableCell();
                        tc.Text       = this.EmptyDataText;
                        tc.ColumnSpan = ColumnCount;

                        gvr.Cells.Add(tc);

                        maintable.Rows.Add(gvr);
                    }
                }
            }
        }
示例#23
0
 public void _InitializeRow(GridViewRow row, DataControlField[] fields)
 {
     base.InitializeRow(row, fields);
 }
示例#24
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="gReport">The g report.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <param name="dataViewFilterOverrides">The data view filter overrides.</param>
        /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param>
        /// <param name="isCommunication">if set to <c>true</c> [is communication].</param>
        /// <param name="errorMessage">The error message.</param>
        public static void BindGrid(Report report, Grid gReport, Person currentPerson, DataViewFilterOverrides dataViewFilterOverrides, int?databaseTimeoutSeconds, bool isCommunication, out string errorMessage)
        {
            errorMessage = null;
            if (report != null)
            {
                var errors = new List <string>();

                if (!report.EntityTypeId.HasValue)
                {
                    gReport.Visible = false;
                    return;
                }

                var rockContext = new RockContext();

                if (!report.IsAuthorized(Authorization.VIEW, currentPerson))
                {
                    gReport.Visible = false;
                    return;
                }

                Type entityType = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).GetEntityType();
                if (entityType == null)
                {
                    errorMessage = string.Format("Unable to determine entityType for {0}", report.EntityType);
                    return;
                }

                gReport.EntityTypeId = report.EntityTypeId;

                bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Get(typeof(Rock.Model.Person), true, rockContext).Id;

                if (isPersonDataSet)
                {
                    gReport.PersonIdField = "Id";
                    gReport.DataKeyNames  = new string[] { "Id" };
                }
                else
                {
                    gReport.PersonIdField = null;
                }

                if (report.EntityTypeId.HasValue)
                {
                    gReport.RowItemText = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).FriendlyName;
                }

                List <EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields(entityType, true, false);

                var selectedEntityFields = new Dictionary <int, EntityField>();
                var selectedAttributes   = new Dictionary <int, AttributeCache>();
                var selectedComponents   = new Dictionary <int, ReportField>();

                // if there is a selectField, keep it to preserve which items are checked
                var selectField = gReport.Columns.OfType <SelectField>().FirstOrDefault();
                gReport.Columns.Clear();
                int columnIndex = 0;

                if (!string.IsNullOrWhiteSpace(gReport.PersonIdField))
                {
                    // if we already had a selectField, use it (to preserve checkbox state)
                    gReport.Columns.Add(selectField ?? new SelectField());
                    columnIndex++;
                }

                var reportFieldSortExpressions = new Dictionary <Guid, string>();

                gReport.CommunicateMergeFields = new List <string>();
                gReport.CommunicationRecipientPersonIdFields = new List <string>();

                foreach (var reportField in report.ReportFields.OrderBy(a => a.ColumnOrder))
                {
                    bool mergeField     = reportField.IsCommunicationMergeField.HasValue && reportField.IsCommunicationMergeField.Value;
                    bool recipientField = reportField.IsCommunicationRecipientField.HasValue && reportField.IsCommunicationRecipientField.Value;

                    columnIndex++;
                    if (reportField.ReportFieldType == ReportFieldType.Property)
                    {
                        var entityField = entityFields.FirstOrDefault(a => a.Name == reportField.Selection);
                        if (entityField != null)
                        {
                            selectedEntityFields.Add(columnIndex, entityField);

                            BoundField boundField = entityField.GetBoundFieldType();
                            boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                            boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? entityField.Title : reportField.ColumnHeaderText;
                            boundField.SortExpression = boundField.DataField;
                            reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);
                            boundField.Visible = reportField.ShowInGrid;
                            gReport.Columns.Add(boundField);

                            if (mergeField)
                            {
                                gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                            }
                            if (recipientField)
                            {
                                gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                            }
                        }
                    }
                    else if (reportField.ReportFieldType == ReportFieldType.Attribute)
                    {
                        Guid?attributeGuid = reportField.Selection.AsGuidOrNull();
                        if (attributeGuid.HasValue)
                        {
                            var attribute = AttributeCache.Get(attributeGuid.Value, rockContext);
                            if (attribute != null && attribute.IsActive)
                            {
                                selectedAttributes.Add(columnIndex, attribute);

                                BoundField boundField;

                                if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.BOOLEAN.AsGuid()))
                                {
                                    boundField = new BoolField();
                                }
                                else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid()))
                                {
                                    boundField = new DefinedValueField();
                                }
                                else
                                {
                                    boundField            = new CallbackField();
                                    boundField.HtmlEncode = false;
                                    (boundField as CallbackField).OnFormatDataValue += (sender, e) =>
                                    {
                                        string resultHtml     = null;
                                        var    attributeValue = e.DataValue ?? attribute.DefaultValueAsType;
                                        if (attributeValue != null)
                                        {
                                            bool condensed = true;
                                            resultHtml = attribute.FieldType.Field.FormatValueAsHtml(gReport, attributeValue.ToString(), attribute.QualifierValues, condensed);
                                        }

                                        e.FormattedValue = resultHtml ?? string.Empty;
                                    };
                                }

                                boundField.DataField      = string.Format("Attribute_{0}_{1}", attribute.Id, columnIndex);
                                boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? attribute.Name : reportField.ColumnHeaderText;
                                boundField.SortExpression = boundField.DataField;
                                reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);

                                if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) ||
                                    attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DATE.AsGuid()) ||
                                    attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid()))
                                {
                                    boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                                    boundField.ItemStyle.HorizontalAlign   = HorizontalAlign.Right;
                                }

                                boundField.Visible = reportField.ShowInGrid;

                                gReport.Columns.Add(boundField);

                                if (mergeField)
                                {
                                    gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                                }
                                if (recipientField)
                                {
                                    gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                                }
                            }
                        }
                    }
                    else if (reportField.ReportFieldType == ReportFieldType.DataSelectComponent)
                    {
                        selectedComponents.Add(columnIndex, reportField);

                        DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.DataSelectComponentEntityType.Name);
                        if (selectComponent != null)
                        {
                            try
                            {
                                DataControlField columnField = selectComponent.GetGridField(entityType, reportField.Selection ?? string.Empty);
                                string           fieldId     = $"{selectComponent.ColumnPropertyName}_{columnIndex}";

                                if (columnField is BoundField)
                                {
                                    (columnField as BoundField).DataField = $"Data_{fieldId}";
                                    var  customSortProperties = selectComponent.SortProperties(reportField.Selection ?? string.Empty);
                                    bool sortReversed         = selectComponent.SortReversed(reportField.Selection ?? string.Empty);
                                    if (customSortProperties != null)
                                    {
                                        if (customSortProperties == string.Empty)
                                        {
                                            // disable sorting if customSortExpression set to string.empty
                                            columnField.SortExpression = string.Empty;
                                        }
                                        else
                                        {
                                            columnField.SortExpression = customSortProperties.Split(',').Select(a => string.Format("Sort_{0}_{1}", a, columnIndex)).ToList().AsDelimited(",");
                                        }
                                    }
                                    else
                                    {
                                        // use default sorting if customSortExpression was null
                                        columnField.SortExpression = (columnField as BoundField).DataField;
                                    }

                                    if (sortReversed == true && !string.IsNullOrWhiteSpace(columnField.SortExpression))
                                    {
                                        columnField.SortExpression = columnField.SortExpression + " DESC";
                                    }
                                }

                                columnField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText;
                                if (!string.IsNullOrEmpty(columnField.SortExpression))
                                {
                                    reportFieldSortExpressions.AddOrReplace(reportField.Guid, columnField.SortExpression);
                                }

                                columnField.Visible = reportField.ShowInGrid;
                                gReport.Columns.Add(columnField);

                                if (mergeField)
                                {
                                    gReport.CommunicateMergeFields.Add($"Data_{fieldId}|{columnField.HeaderText.RemoveSpecialCharacters()}");
                                }
                                if (recipientField)
                                {
                                    string fieldName = (selectComponent is IRecipientDataSelect) ? $"Recipient_{fieldId}" : $"Data_{fieldId}";
                                    gReport.CommunicationRecipientPersonIdFields.Add(fieldName);
                                }
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogService.LogException(ex, HttpContext.Current);
                                errors.Add(string.Format("{0} - {1}", selectComponent, ex.Message));
                            }
                        }
                    }
                }

                // if no fields are specified, show the default fields (Previewable/All) for the EntityType
                var dataColumns = gReport.Columns.OfType <object>().Where(a => a.GetType() != typeof(SelectField));
                if (dataColumns.Count() == 0)
                {
                    // show either the Previewable Columns or all (if there are no previewable columns)
                    bool showAllColumns = !entityFields.Any(a => a.FieldKind == FieldKind.Property && a.IsPreviewable);
                    foreach (var entityField in entityFields.Where(a => a.FieldKind == FieldKind.Property))
                    {
                        columnIndex++;
                        selectedEntityFields.Add(columnIndex, entityField);

                        BoundField boundField = entityField.GetBoundFieldType();

                        boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                        boundField.HeaderText     = entityField.Name;
                        boundField.SortExpression = boundField.DataField;
                        boundField.Visible        = showAllColumns || entityField.IsPreviewable;
                        gReport.Columns.Add(boundField);
                    }
                }

                try
                {
                    gReport.Visible        = true;
                    gReport.ExportFilename = report.Name;
                    SortProperty sortProperty = gReport.SortProperty;
                    if (sortProperty == null)
                    {
                        var reportSort  = new SortProperty();
                        var sortColumns = new Dictionary <string, SortDirection>();
                        foreach (var reportField in report.ReportFields.Where(a => a.SortOrder.HasValue).OrderBy(a => a.SortOrder.Value))
                        {
                            if (reportFieldSortExpressions.ContainsKey(reportField.Guid))
                            {
                                var sortField = reportFieldSortExpressions[reportField.Guid];
                                if (!string.IsNullOrWhiteSpace(sortField))
                                {
                                    sortColumns.Add(sortField, reportField.SortDirection);
                                }
                            }
                        }

                        if (sortColumns.Any())
                        {
                            reportSort.Property = sortColumns.Select(a => a.Key + (a.Value == SortDirection.Descending ? " desc" : string.Empty)).ToList().AsDelimited(",");
                            sortProperty        = reportSort;
                        }
                    }

                    var qryErrors = new List <string>();
                    System.Data.Entity.DbContext reportDbContext;
                    dynamic qry = report.GetQueryable(entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, dataViewFilterOverrides, databaseTimeoutSeconds ?? 180, isCommunication, out qryErrors, out reportDbContext);
                    errors.AddRange(qryErrors);

                    if (!string.IsNullOrEmpty(report.QueryHint) && reportDbContext is RockContext)
                    {
                        using (new QueryHintScope(reportDbContext as RockContext, report.QueryHint))
                        {
                            gReport.SetLinqDataSource(qry);
                        }
                    }
                    else
                    {
                        gReport.SetLinqDataSource(qry);
                    }

                    gReport.DataBind();
                }
                catch (Exception ex)
                {
                    Exception exception = ex;
                    ExceptionLogService.LogException(ex, HttpContext.Current);
                    while (exception != null)
                    {
                        if (exception is System.Data.SqlClient.SqlException)
                        {
                            // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                            if ((exception as System.Data.SqlClient.SqlException).Number == -2)
                            {
                                errorMessage = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                                return;
                            }
                            else
                            {
                                errors.Add(exception.Message);
                                exception = exception.InnerException;
                            }
                        }
                        else
                        {
                            errors.Add(exception.Message);
                            exception = exception.InnerException;
                        }
                    }
                }

                if (errors.Any())
                {
                    errorMessage = "WARNING: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited("<br/>");
                }
            }
        }
示例#25
0
            protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
            {
                int numRows = base.CreateChildControls(dataSource, dataBinding);

                //no data rows created, create 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);

                    if (this.ShowFooter && this.ShowEmptyFooter)
                    {
                        GridViewRow foot = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
                        this.Columns.CopyTo(fields, 0);
                        this.InitializeRow(foot, fields);
                        table.Rows.Add(foot);
                    }

                    this.Controls.Add(table);
                }

                return numRows;
            }
示例#26
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="gReport">The g report.</param>
        /// <param name="bindGridOptions">The bind grid options.</param>
        /// <exception cref="ArgumentNullException">Report must be specified</exception>
        /// <exception cref="Rock.Reporting.RockReportingException">Unable to determine EntityType type for {report.EntityType}</exception>
        public static void BindGrid(Report report, Grid gReport, BindGridOptions bindGridOptions)
        {
            if (report == null)
            {
                throw new ArgumentNullException("Report must be specified");
            }

            if (!report.EntityTypeId.HasValue)
            {
                gReport.Visible = false;
                return;
            }

            var currentPerson = bindGridOptions?.CurrentPerson;

            var rockContext = new RockContext();

            if (!report.IsAuthorized(Authorization.VIEW, currentPerson))
            {
                gReport.Visible = false;
                return;
            }

            Type entityType = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).GetEntityType();

            if (entityType == null)
            {
                throw new RockReportException(report, $"Unable to determine EntityType type for {report.EntityType} ");
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            gReport.EntityTypeId = report.EntityTypeId;

            bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Get(typeof(Rock.Model.Person), true, rockContext).Id;

            if (isPersonDataSet)
            {
                gReport.PersonIdField = "Id";
                gReport.DataKeyNames  = new string[] { "Id" };
            }
            else
            {
                gReport.PersonIdField = null;
            }

            if (report.EntityTypeId.HasValue)
            {
                gReport.RowItemText = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).FriendlyName;
            }

            List <EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields(entityType, true, false);

            var selectedEntityFields = new Dictionary <int, EntityField>();
            var selectedAttributes   = new Dictionary <int, AttributeCache>();
            var selectedComponents   = new Dictionary <int, ReportField>();

            // if there is a selectField, keep it to preserve which items are checked
            var selectField = gReport.Columns.OfType <SelectField>().FirstOrDefault();

            gReport.Columns.Clear();
            int columnIndex = 0;

            if (!string.IsNullOrWhiteSpace(gReport.PersonIdField))
            {
                // if we already had a selectField, use it (to preserve checkbox state)
                gReport.Columns.Add(selectField ?? new SelectField());
                columnIndex++;
            }

            var reportFieldSortExpressions = new Dictionary <Guid, string>();

            gReport.CommunicateMergeFields = new List <string>();
            gReport.CommunicationRecipientPersonIdFields = new List <string>();

            foreach (var reportField in report.ReportFields.OrderBy(a => a.ColumnOrder))
            {
                bool isMergeField     = reportField.IsCommunicationMergeField.HasValue && reportField.IsCommunicationMergeField.Value;
                bool isRecipientField = reportField.IsCommunicationRecipientField.HasValue && reportField.IsCommunicationRecipientField.Value;

                columnIndex++;
                if (reportField.ReportFieldType == ReportFieldType.Property)
                {
                    var entityField = entityFields.FirstOrDefault(a => a.Name == reportField.Selection);

                    if (entityField == null)
                    {
                        // if the reportField selection refers to a non-existant entityField, ignore this field
                        continue;
                    }

                    selectedEntityFields.Add(columnIndex, entityField);

                    BoundField boundField = entityField.GetBoundFieldType();
                    boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                    boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? entityField.Title : reportField.ColumnHeaderText;
                    boundField.SortExpression = boundField.DataField;
                    reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);
                    boundField.Visible = reportField.ShowInGrid;
                    gReport.Columns.Add(boundField);

                    if (isMergeField)
                    {
                        gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                    }

                    if (isRecipientField)
                    {
                        gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                    }
                }
                else if (reportField.ReportFieldType == ReportFieldType.Attribute)
                {
                    Guid?attributeGuid = reportField.Selection.AsGuidOrNull();
                    if (attributeGuid == null)
                    {
                        // if an attribute guid is not specified, just ignore this field
                        continue;
                    }

                    var attribute = AttributeCache.Get(attributeGuid.Value, rockContext);
                    if (attribute == null || !attribute.IsActive)
                    {
                        // if the attribute doesn't exist (or no longer exists), or if the active is not active, just ignore this field
                        continue;
                    }

                    selectedAttributes.Add(columnIndex, attribute);

                    BoundField boundField;

                    if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.BOOLEAN.AsGuid()))
                    {
                        boundField = new BoolField();
                    }
                    else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid()))
                    {
                        boundField = new DefinedValueField();
                    }
                    else
                    {
                        boundField            = new CallbackField();
                        boundField.HtmlEncode = false;
                        (boundField as CallbackField).OnFormatDataValue += (sender, e) =>
                        {
                            string resultHtml     = null;
                            var    attributeValue = e.DataValue ?? attribute.DefaultValueAsType;
                            if (attributeValue != null)
                            {
                                bool condensed = true;
                                resultHtml = attribute.FieldType.Field.FormatValueAsHtml(gReport, attributeValue.ToString(), attribute.QualifierValues, condensed);
                            }

                            e.FormattedValue = resultHtml ?? string.Empty;
                        };
                    }

                    boundField.DataField      = string.Format("Attribute_{0}_{1}", attribute.Id, columnIndex);
                    boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? attribute.Name : reportField.ColumnHeaderText;
                    boundField.SortExpression = boundField.DataField;
                    reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);

                    if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) ||
                        attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DATE.AsGuid()) ||
                        attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid()))
                    {
                        boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                        boundField.ItemStyle.HorizontalAlign   = HorizontalAlign.Right;
                    }

                    boundField.Visible = reportField.ShowInGrid;

                    gReport.Columns.Add(boundField);

                    if (isMergeField)
                    {
                        gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                    }

                    if (isRecipientField)
                    {
                        gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                    }
                }
                else if (reportField.ReportFieldType == ReportFieldType.DataSelectComponent)
                {
                    selectedComponents.Add(columnIndex, reportField);

                    DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.DataSelectComponentEntityType.Name);
                    if (selectComponent == null)
                    {
                        throw new RockReportFieldExpressionException(reportField, $"Unable to determine select component for {reportField.DataSelectComponentEntityType.Name}");
                    }

                    DataControlField columnField = selectComponent.GetGridField(entityType, reportField.Selection ?? string.Empty);
                    string           fieldId     = $"{selectComponent.ColumnPropertyName}_{columnIndex}";

                    if (columnField is BoundField)
                    {
                        (columnField as BoundField).DataField = $"Data_{fieldId}";
                        var  customSortProperties = selectComponent.SortProperties(reportField.Selection ?? string.Empty);
                        bool sortReversed         = selectComponent.SortReversed(reportField.Selection ?? string.Empty);
                        if (customSortProperties != null)
                        {
                            if (customSortProperties == string.Empty)
                            {
                                // disable sorting if customSortExpression set to string.empty
                                columnField.SortExpression = string.Empty;
                            }
                            else
                            {
                                columnField.SortExpression = customSortProperties.Split(',').Select(a => string.Format("Sort_{0}_{1}", a, columnIndex)).ToList().AsDelimited(",");
                            }
                        }
                        else
                        {
                            // use default sorting if customSortExpression was null
                            columnField.SortExpression = (columnField as BoundField).DataField;
                        }

                        if (sortReversed == true && !string.IsNullOrWhiteSpace(columnField.SortExpression))
                        {
                            columnField.SortExpression = columnField.SortExpression + " DESC";
                        }
                    }

                    columnField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText;
                    if (!string.IsNullOrEmpty(columnField.SortExpression))
                    {
                        reportFieldSortExpressions.AddOrReplace(reportField.Guid, columnField.SortExpression);
                    }

                    columnField.Visible = reportField.ShowInGrid;
                    gReport.Columns.Add(columnField);

                    if (isMergeField)
                    {
                        gReport.CommunicateMergeFields.Add($"Data_{fieldId}|{columnField.HeaderText.RemoveSpecialCharacters()}");
                    }
                    if (isRecipientField)
                    {
                        string fieldName = (selectComponent is IRecipientDataSelect) ? $"Recipient_{fieldId}" : $"Data_{fieldId}";
                        gReport.CommunicationRecipientPersonIdFields.Add(fieldName);
                    }
                }
            }

            // if no fields are specified, show the default fields (Previewable/All) for the EntityType
            var dataColumns = gReport.Columns.OfType <object>().Where(a => a.GetType() != typeof(SelectField));

            if (dataColumns.Count() == 0)
            {
                // show either the Previewable Columns or all (if there are no previewable columns)
                bool showAllColumns = !entityFields.Any(a => a.FieldKind == FieldKind.Property && a.IsPreviewable);
                foreach (var entityField in entityFields.Where(a => a.FieldKind == FieldKind.Property))
                {
                    columnIndex++;
                    selectedEntityFields.Add(columnIndex, entityField);

                    BoundField boundField = entityField.GetBoundFieldType();

                    boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                    boundField.HeaderText     = entityField.Name;
                    boundField.SortExpression = boundField.DataField;
                    boundField.Visible        = showAllColumns || entityField.IsPreviewable;
                    gReport.Columns.Add(boundField);
                }
            }

            try
            {
                gReport.Visible        = true;
                gReport.ExportFilename = report.Name;
                SortProperty sortProperty = gReport.SortProperty;
                if (sortProperty == null)
                {
                    var reportSort  = new SortProperty();
                    var sortColumns = new Dictionary <string, SortDirection>();
                    foreach (var reportField in report.ReportFields.Where(a => a.SortOrder.HasValue).OrderBy(a => a.SortOrder.Value))
                    {
                        if (reportFieldSortExpressions.ContainsKey(reportField.Guid))
                        {
                            var sortField = reportFieldSortExpressions[reportField.Guid];
                            if (!string.IsNullOrWhiteSpace(sortField))
                            {
                                sortColumns.Add(sortField, reportField.SortDirection);
                            }
                        }
                    }

                    if (sortColumns.Any())
                    {
                        reportSort.Property = sortColumns.Select(a => a.Key + (a.Value == SortDirection.Descending ? " desc" : string.Empty)).ToList().AsDelimited(",");
                        sortProperty        = reportSort;
                    }
                }

                var qryErrors       = new List <string>();
                var reportDbContext = bindGridOptions?.ReportDbContext;
                if (reportDbContext == null)
                {
                    reportDbContext = Reflection.GetDbContextForEntityType(entityType);
                }

                ReportGetQueryableArgs reportGetQueryableArgs = new ReportGetQueryableArgs
                {
                    ReportDbContext         = reportDbContext as Rock.Data.DbContext,
                    EntityFields            = selectedEntityFields,
                    Attributes              = selectedAttributes,
                    SelectComponents        = selectedComponents,
                    SortProperty            = sortProperty,
                    DataViewFilterOverrides = bindGridOptions?.DataViewFilterOverrides,
                    DatabaseTimeoutSeconds  = bindGridOptions?.DatabaseTimeoutSeconds ?? 180,
                    IsCommunication         = bindGridOptions?.IsCommunication ?? false
                };

                dynamic qry = report.GetQueryable(reportGetQueryableArgs);

                if (!string.IsNullOrEmpty(report.QueryHint) && reportDbContext is RockContext)
                {
                    using (new QueryHintScope(reportDbContext as RockContext, report.QueryHint))
                    {
                        gReport.SetLinqDataSource(qry);
                    }
                }
                else
                {
                    gReport.SetLinqDataSource(qry);
                }

                gReport.DataBind();
                stopwatch.Stop();

                ReportService.AddRunReportTransaction(report.Id, Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds));
            }
            catch (Exception ex)
            {
                Exception exception = ex;
                ExceptionLogService.LogException(ex, HttpContext.Current);

                // recursively find if there was a SQL timeout exception.
                // A SQL Timeout would be something we might expect, so we'll give that a friendly error message.
                var sqlTimeoutException = FindSqlTimeoutException(ex);

                if (sqlTimeoutException != null)
                {
                    // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                    throw new RockReportException(report, "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.", ex);
                }

                // if there isn't a SQL Exception, we'll throw the original exception (since it would be an exception that we wouldn't expect)
                throw;
            }
        }
示例#27
0
 protected override void CopyProperties(DataControlField newField)
 {
     base.CopyProperties(newField);
     ((CollapseHandleField)(newField)).OpenCssClass     = this.OpenCssClass;
     ((CollapseHandleField)(newField)).CollapseCssClass = this.CollapseCssClass;
 }
        private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
        {
            if (rows.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag(tableSection);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (GridViewRow row in rows)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("tr");

                    string className = GetRowClass(gridView, row);
                    if (!String.IsNullOrEmpty(className))
                    {
                        writer.WriteAttribute("class", className);
                    }

                    //  Uncomment the following block of code if you want to add arbitrary attributes.

                    /*
                     * foreach (string key in row.Attributes.Keys)
                     * {
                     *  writer.WriteAttribute(key, row.Attributes[key]);
                     * }
                     */

                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;

                    foreach (TableCell cell in row.Cells)
                    {
                        DataControlFieldCell fieldCell = cell as DataControlFieldCell;
                        if ((fieldCell != null) && (fieldCell.ContainingField != null))
                        {
                            DataControlField field = fieldCell.ContainingField;
                            if (!field.Visible)
                            {
                                cell.Visible = false;
                            }

                            if ((field.ItemStyle != null) && (!String.IsNullOrEmpty(field.ItemStyle.CssClass)))
                            {
                                if (!String.IsNullOrEmpty(cell.CssClass))
                                {
                                    cell.CssClass += " ";
                                }
                                cell.CssClass += field.ItemStyle.CssClass;
                            }
                        }

                        writer.WriteLine();
                        cell.RenderControl(writer);
                    }

                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("tr");
                }

                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag(tableSection);
            }
        }
示例#29
0
        /// <summary>
        /// 将GridView数据导出到Excel表格中。
        /// </summary>
        /// <param name="gvCtrl">要导出数据的GridView控件。</param>
        /// <param name="needToHideColumnIndexes">需要隐藏的GridView的列索引数组</param>
        /// <param name="exportTitle">导出标题</param>
        /// <param name="fileName">导出文件名</param>
        static public void ExportToExcel(System.Web.UI.WebControls.GridView gvCtrl,
                                         int[] needToHideColumnIndexes, string exportTitle, string fileName)
        {
            if (string.IsNullOrEmpty(exportTitle))
            {
                exportTitle = Properties.Resources.ExportTitle;
            }

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Properties.Resources.ExportFile;
            }

            //  记录GridView原始信息。
            bool isSorting = gvCtrl.AllowSorting;
            int  pageIndex = gvCtrl.PageIndex;
            int  pageSize  = gvCtrl.PageSize;

            //  设置GridView状态信息。
            Dictionary <int, bool> visibleStates = new Dictionary <int, bool>();

            for (int i = 0; i < gvCtrl.Columns.Count; i++)
            {
                DataControlField aCol = gvCtrl.Columns[i];
                visibleStates[i] = aCol.Visible;

                bool bContains = false;
                foreach (int x in needToHideColumnIndexes)
                {
                    if (x == i)
                    {
                        bContains = true;
                        break;
                    }
                }

                aCol.Visible = (needToHideColumnIndexes == null || !bContains);
            }

            //gvCtrl.AllowPaging = false;
            gvCtrl.AllowSorting = false;

            gvCtrl.PageSize  = (gvCtrl.PageSize * gvCtrl.PageCount <= 0 ? 1 : gvCtrl.PageSize * gvCtrl.PageCount);
            gvCtrl.PageIndex = 0;

            //  绑定GridView。
            gvCtrl.DataBind();

            //  处理输出流。
            System.Web.HttpContext context = System.Web.HttpContext.Current;

            context.Response.Clear();

            context.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            context.Response.ContentType = "application/vnd.ms-excel";

            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            context.Response.Charset         = "GB2312";

            System.IO.StringWriter       sw  = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            gvCtrl.RenderControl(htw);

            context.Response.Write(exportTitle);
            context.Response.Write(sw.ToString());
            context.Response.End();

            //  还原GridView状态信息。
            for (int i = 0; i < gvCtrl.Columns.Count; i++)
            {
                DataControlField aCol = gvCtrl.Columns[i];
                aCol.Visible = visibleStates[i];
            }

            gvCtrl.AllowSorting = isSorting;

            gvCtrl.PageSize  = pageSize;
            gvCtrl.PageIndex = pageIndex;
        }
	public void CopyTo(DataControlField[] array, int index) {}
示例#31
0
 protected override void CopyProperties(DataControlField newField)
 {
     throw new NotImplementedException();
 }
	public void Insert(int index, DataControlField field) {}
 public abstract TemplateField CreateTemplateField(DataControlField dataControlField, DataBoundControl dataBoundControl);
	// Methods
	public void Add(DataControlField field) {}
 public abstract string GetNodeText(DataControlField dataControlField);
示例#36
0
    public string GetDataFieldName(DataControlField field)
    {
        // TO DO: Enable search in HyperLinkField, ButtonField...

        if (field is BoundField)
        {
            return (field as BoundField).DataField;
        }
        else
        {
            // It hopes that SortExpression is set (and it's equal to column name)
            return field.SortExpression;
        }
    }
 protected TemplateField GetTemplateField(DataControlField dataControlField, DataBoundControl dataBoundControl)
 {
     return(DataControlFieldHelper.GetTemplateField(dataControlField, dataBoundControl));
 }
    // pageIndex start at 1
    public void BindData(int pageIndex)
    {
        ExchangeVoucherHeaderDataSource ds = InitDataSource();
        EmptyGridViewEx1.DataSourceObject = ds.Select(pageSize, (pageIndex - 1) * pageSize);
        EmptyGridViewEx1.DataBind();

        // setting paging
        int page;
        cmdFirst.CommandArgument = "1";
        cmdLast.CommandArgument = ds.PageCount.ToString();
        page = (ds.PageIndex > 0) ? ds.PageIndex : 1; // ? PageIndex + 1 - 1 : 1
        cmdPrevious.CommandArgument = page.ToString();
        page = ((ds.PageIndex + 1) < ds.PageCount) ? ds.PageIndex + 2 : ds.PageCount;
        cmdNext.CommandArgument = page.ToString();
        litPageInfo.Text = string.Format(Message.PagingInfo, ds.PageIndex + 1, ds.PageCount, ds.ItemCount);
        pnPager.Visible = ds.PageCount > 1;
        pnAllPageSummary.Visible = (ds.PageCount > 0) && this.ShowAllPageSummary;

        if (EmptyGridViewEx1.Rows.Count > 0)
        {
            // show total infos
            NumberFormatInfo ni = (NumberFormatInfo)Thread.CurrentThread.CurrentCulture.NumberFormat.Clone();
            ni.NumberDecimalDigits = 0;

            #region total of all
            if (this.ShowFooter)       //(ds.PageCount > 1)
            {
                GridViewRow frow = EmptyGridViewEx1.FootRow;    // clone footer
                if (frow != null)
                {
                    for (int i = 0; i < totalFootColSpan; i++) { frow.Cells.RemoveAt(0); }
                    frow.Cells[0].ColumnSpan = totalFootColSpan + 1; frow.Cells[0].CssClass = "summaryName";
                    frow.Cells[0].Text = Constants.DealerAllTotal;
                    frow.Cells[1].Text = ds.TotalSparesO.ToString("N", ni); frow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                    frow.Cells[3].Text = ds.TotalAmountO.ToString("N", ni);
                    frow.Cells[5].Text = ds.TotalFeeO.ToString("N", ni);
                    frow.Cells[7].Text = ds.AllTotalO.ToString("N", ni);
                }

                //create a new foot row
                GridViewRow row = EmptyGridViewEx1._CreateRow(0, -1, DataControlRowType.Footer, DataControlRowState.Normal);
                DataControlField[] fields = new DataControlField[EmptyGridViewEx1.Columns.Count];
                EmptyGridViewEx1.Columns.CopyTo(fields, 0);
                EmptyGridViewEx1._InitializeRow(row, fields);
                for (int i = 0; i < totalFootColSpan; i++) { row.Cells.RemoveAt(0); }
                for (int i = 1; i < row.Cells.Count; i++) { row.Cells[i].CssClass = "changedValue"; }
                row.Cells[0].ColumnSpan = totalFootColSpan + 1; row.Cells[0].CssClass = "summaryName";

                row.Cells[0].Text = Constants.VMEPAllTotal;
                row.Cells[1].Text = ds.TotalSparesM.ToString("N", ni); frow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                row.Cells[3].Text = ds.TotalAmountM.ToString("N", ni);
                row.Cells[6].Text = ds.TotalFeeM.ToString("N", ni);
                row.Cells[7].Text = ds.AllTotalM.ToString("N", ni);
                EmptyGridViewEx1.Controls[0].Controls.Add(row);

                if (ShowAllPageSummary) ShowAllPageTotal(ds);
            }
            #endregion
        }
        pnDealer.Visible = OnVerify;
        //dealer info
        if (OnVerify)
        {
            litDealerCode.Text = ds.DealerCode;
            litDealerName.Text = ds.DealerName;
        }

        // command visibility
        EmptyGridViewEx1.Columns[EmptyGridViewEx1.Columns.Count - 1].Visible = ShowVerifyButton;
        EmptyGridViewEx1.Columns[EmptyGridViewEx1.Columns.Count - 3].Visible = ShowEditButton;
    }
示例#39
0
        private void PopulateForm(int?specimenAccessionId)
        {
            bool isNewAccession = !specimenAccessionId.HasValue;
            int  patientId      = int.Parse(BaseDecryptedPatientId);
            int  ptProtocolId   = int.Parse(PatientProtocolId);

            // set study id
            PatientProtocol ptProtocol = new PatientProtocol();

            if (!string.IsNullOrEmpty(PatientProtocolId))
            {
                ptProtocol.Get(int.Parse(PatientProtocolId));
                PtProtocolStudyId.Value = ptProtocol[PatientProtocol.PtProtocolStudyId].ToString();
            }

            // populate SpecimenAccessions
            SpecimenAccession sa = new SpecimenAccession();

            if (specimenAccessionId.HasValue)
            {
                sa.Get(specimenAccessionId.Value);
                base.PopulateForm(sa);
                // special case: needle
                PopulateNeedleUIField(sa);
                // special case: diagnostics for tissue
                if (QuerySpecimenType == QUERY_TISSUE) // && !string.IsNullOrEmpty(AccessionProcName.Text) && AccessionProcName.Text.StartsWith("Image-Guided", StringComparison.OrdinalIgnoreCase))
                {
                    PopulateDiagnostic(specimenAccessionId.Value);
                }
            }

            // populate Specimens grid
            DataView specimens;

            // STEP 1: get all accessions of this type, will filter later on
            specimens = da.GetSpecimenReport(ptProtocolId, null, QuerySpecimenType).DefaultView;
            var allSpecimentRefNum = specimens.Table.AsEnumerable().Select(r => r[Specimen.SpecimenReferenceNumber].ToString()).Distinct();

            // STEP 2: generate an auto-calculated spec ref num for the patient (exclude currently assigned)
            autoGeneratedSpecimenRefNum.Clear();
            // only auto-generate spec # if filtering by type + visit
            if (!string.IsNullOrEmpty(QuerySpecimenType) && !string.IsNullOrEmpty(QueryVisitType))
            {
                int totalSpecimens = SpecimensGrid.BlankRows + specimens.Count;
                int start          = 1;
                // find the max currently assigned reference num
                for (int seqNum = 1; seqNum <= totalSpecimens; seqNum++)
                {
                    // check if currently assigned, else add to available bucket
                    if (allSpecimentRefNum.Contains(GetSpecimenReferenceNumber(seqNum + "")))
                    {
                        start += 1;
                    }
                }
                // fill auto ref num
                autoGeneratedSpecimenRefNum.AddRange(Enumerable.Range(start, totalSpecimens).Select(seqNum => GetSpecimenReferenceNumber(seqNum + "")));
            }
            // when no parent record specified, build estimated reference num, but do not popualte with exisiting data
            if (!specimenAccessionId.HasValue)
            {
                specimens.Table.Clear();
            }

            // build restrictions
            List <string> restrictions = new List <string>();

            // restrict to this accession
            if (specimenAccessionId.HasValue)
            {
                restrictions.Add(Specimen.SpecimenAccessionId + " = " + specimenAccessionId.Value);
            }
            // restrict to this type
            if (!string.IsNullOrEmpty(QuerySpecimenType))
            {
                restrictions.Add(Specimen.SpecimenType + " = '" + QuerySpecimenType + "'");
                // restrict to visit (requires specimen type)
                if (!string.IsNullOrEmpty(QueryVisitType))
                {
                    string refNumMatch = GetSpecimenReferenceNumber("");
                    restrictions.Add(Specimen.SpecimenReferenceNumber + " LIKE '" + PageUtil.EscapeSingleQuotesForSql(refNumMatch) + "%'");
                }
            }


            if (restrictions.Count() > 0)
            {
                specimens.RowFilter = string.Join(" AND ", restrictions.ToArray());
                specimens           = new DataView(specimens.ToTable());
            }
            else
            {
                specimens.RowFilter = "";
            }

            // data binding

            // adjust subType heading
            DataControlField subTypeColumn          = SpecimensGrid.Columns[1];
            DataControlField vialTypeColumn         = SpecimensGrid.Columns[2];
            DataControlField processingMethodColumn = SpecimensGrid.Columns[3];
            DataControlField specimenStatusColumn   = SpecimensGrid.Columns[6];

            if (QuerySpecimenType == QUERY_TISSUE)
            {
                // custom visits ??
                bool customVisits = BuildSpecimenVisitTypes(QUERY_TISSUE, sa);

                subTypeColumn.HeaderText = "Sample Type";
                // hide columns from UI
                foreach (DataControlField column in new DataControlField[] { subTypeColumn, subTypeColumn, vialTypeColumn })
                {
                    column.HeaderStyle.CssClass = "hidden";
                    column.ItemStyle.CssClass   = "hidden";
                }

                // set selection in parent
                Tissue_SpecimenSubType.Value = specimens.Count > 0 ? specimens[0][Specimen.SpecimenSubType].ToString() : "";

                // blank rows
                SpecimensGrid.BlankRows        = Math.Max(0, 6 - specimens.Count);
                SpecimensGrid.VisibleBlankRows = 1;
                if (SpecimensGrid.BlankRows == 0)
                {
                    AddBtn.Visible = false;
                }
                if (specimens.Count != 0)
                {
                    SpecimensGrid.VisibleBlankRows = 0;
                }
            }
            else if (QuerySpecimenType == QUERY_BLOOD)
            {
                // custom visits ??
                bool customVisits = BuildSpecimenVisitTypes(QUERY_BLOOD, sa);
                // static visits
                if (!customVisits)
                {
                    // default accession visit
                    AccessionVisit.Value   = "A";
                    AccessionVisit.Enabled = false;
                }

                AddBtn.Visible           = true;
                subTypeColumn.HeaderText = "Tube Use";

                // hide columns from UI
                foreach (DataControlField column in new DataControlField[] { processingMethodColumn })
                {
                    column.HeaderStyle.CssClass = "hidden";
                    column.ItemStyle.CssClass   = "hidden";
                }
                // update default blood specimens
                bloodAutoSpecimens = ProtocolMgmtSpecimenController.GetBloodAutoSpecimenIds(base.ProtocolNumber, (int)ptProtocol[PatientProtocol.PatientProtocolId], PtProtocolStudyId.Value, AccessionVisit.Enabled ? AccessionVisit.Value : "");

                SpecimensGrid.BlankRows        = Math.Max(0, 15 - specimens.Count);
                SpecimensGrid.VisibleBlankRows = specimens.Count > 0 ? 0 : (bloodAutoSpecimens.Length > 0 ? bloodAutoSpecimens.Length : 3);
                AddBtn.Visible = SpecimensGrid.BlankRows > 0;
            }

            SpecimensGrid.DataSource = specimens;
            SpecimensGrid.DataBind();
        }