DataBind() public final method

public final DataBind ( ) : void
return void
Exemplo n.º 1
0
        public static void ShowGridAlways(ref GridView gridView, ref DataTable dt, string emptyMessage)
        {
            if (dt.Rows.Count == 0)
            {
                // Remove contraints so an empty row can be added.
                dt.Constraints.Clear();
                foreach (DataColumn dc in dt.Columns)
                    dc.AllowDBNull = true;

                // Add a blank row to the dataset
                dt.Columns[0].AllowDBNull = true;
                dt.Rows.Add(dt.NewRow());
                // Bind the DataSet to the GridView
                gridView.DataSource = dt;
                gridView.DataBind();
                // Get the number of columns to know what the Column Span should be
                int columnCount = gridView.Rows[0].Cells.Count;
                // Call the clear method to clear out any controls that you use in the columns.  I use a dropdown list in one of the column so this was necessary.
                gridView.Rows[0].Cells.Clear();
                gridView.Rows[0].Cells.Add(new TableCell());
                gridView.Rows[0].Cells[0].ColumnSpan = columnCount;
                gridView.Rows[0].Cells[0].Text = emptyMessage;
            }
            else
            {
                gridView.DataSource = dt;
                gridView.DataBind();
            }
        }
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewClassAssociates.DataBind();
        }//public void ButtonSubmit_Click()
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewIHaveBroughtSomethingAgainstYouButDontWorryIAmWithYou.DataBind();
        }//public void ButtonSubmit_Click()
Exemplo n.º 4
0
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewEvent.DataBind();
        }//public void ButtonSubmit_Click()
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewItsCalledTheSetupScreenOfScreenOne.DataBind();
        }//public void ButtonSubmit_Click()
Exemplo n.º 6
0
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewKnowledgeBase.DataBind();
        }//public void ButtonSubmit_Click()
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewCharlesSimonyi.DataBind();
            GridViewCharlesSimonyi.DataBind();
        }//public void ButtonSubmit_Click()
Exemplo n.º 8
0
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewLJHookerTaxInvoice.DataBind();
            GridViewLJHookerTaxInvoice.DataBind();
        }//public void ButtonSubmit_Click()
        }//public String public String Feedback

        /// <summary>ButtonSubmit_Click().</summary>
        public void ButtonSubmit_Click
        (
            Object sender,
            EventArgs e
        )
        {
            GridViewAussieHomeLoansTransactionHistory.DataBind();
            GridViewAussieHomeLoansAccountBalance.DataBind();
        }//public void ButtonSubmit_Click()
  }//public String URI

  /// <summary>ButtonFileOpen_Click().</summary>
  public void ButtonFileOpen_Click
  (
   Object sender, 
   EventArgs e
  )
  {
   /*
   XmlDataSourceURIGridView.DataFile = FilenameURI;
   GridViewURI.AllowPaging=false;
   GridViewURI.DataKeyNames=null;
   GridViewURI.DataSourceID = XmlDataSourceURIGridView.ID;
   GridViewURI.DataBind();
   */

   string     exceptionMessage  =  null;
   string     filenameXml       =  null;
   DataSet    dataSet           =  null;
   
   try
   {
    filenameXml                =  FilenameURI;
    if ( string.IsNullOrEmpty( filenameXml ) )
    {
     return;
    }
    UtilityURI.ReadXml
    (
     ref filenameXml,
     ref dataSet,
     ref exceptionMessage,
     ref ColumnNameURI
    );
    if ( exceptionMessage != null )
    {
     Feedback = exceptionMessage;
     return;
    }     	 
    if ( dataSet != null )
    {
     ViewState["URIMaintenancePage_DataSet"] = dataSet;
     GridViewURI.AllowPaging   =  false;
     GridViewURI.AllowSorting  =  false;     
     GridViewURI.DataSourceID  =  null;
     GridViewURI.DataSource    =  dataSet;
     GridViewURI.DataBind();
    }
   }//try
   catch ( Exception exception )
   {
   	exceptionMessage = "Exception: " + exception.Message;
   }
   if ( exceptionMessage != null )
   {
   	Feedback = exceptionMessage;
   }
  }//public void ButtonFileOpen_Click()
Exemplo n.º 11
0
        void gridCommingUpLink_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int index = e.RowIndex;
            List <CommingUpLink> temp = ViewState["CommingUp"] as List <CommingUpLink>;

            temp.RemoveAt(index);
            ViewState["CommingUp"]       = temp;
            gridCommingUpLink.DataSource = temp;
            gridCommingUpLink.DataBind();
        }
Exemplo n.º 12
0
        //#region Repeater控件分页帮定
        ///// <summary #region GridView控件分页帮定
        /// <summary>
        /// GridView控件分页帮定
        /// </summary>
        /// <param name="anpager">AspNetPager分页控件</param>
        /// <param name="strTableName">表名</param>
        /// <param name="strPrimaryKey">表的唯一主建名</param>
        /// <param name="strQuaryCondition">查询Where条件,不含Where</param>
        /// <param name="strOrderCondition">需要排序的字段名</param>
        /// <param name="rptControl">GridView控件</param>
        public void GridViewPagerBindbyRowNumber(Wuqi.Webdiyer.AspNetPager anpager, string strTableName, string strPrimaryKey, string OrgCode, string PositionName, string OrgName, string strOrderCondition, System.Web.UI.WebControls.GridView grvControl)
        {
            string  strsel  = "";
            DataSet dstTemp = new DataSet();

            if (OrgCode != "")
            {
                strsel       = "select * from (select row_number() over (order by " + strOrderCondition + ") as rowno,p.*,o.orgName,case p.IsForbid when 1 then  '是' else '否'end as Forbid from " + strTableName + " and   p.OrgCode like @OrgCode and p.PositionName like @PositionName and o.orgName like @orgName) as result Where (rowno Between " + (anpager.CurrentPageIndex - 1) * anpager.PageSize + " and " + anpager.CurrentPageIndex * anpager.PageSize + ")";
                PositionName = "%" + PositionName + "%";
                OrgName      = "%" + OrgName + "%";
                OrgCode      = "%" + OrgCode + "%";
                SqlParameter[] parameters = { new SqlParameter("@OrgCode", OrgCode), new SqlParameter("@PositionName", PositionName), new SqlParameter("@orgName", OrgName) };
                parameters[0].Value = OrgCode;
                parameters[1].Value = PositionName;
                parameters[2].Value = OrgName;

                anpager.RecordCount = Convert.ToInt32(DbHelperSQL.GetSingle("Select Count(*) From " + strTableName + " and  p.OrgCode like @OrgCode and p.PositionName like @PositionName and o.orgName like @orgName ", parameters));
                dstTemp             = DbHelperSQL.Query(strsel, parameters);
            }
            else
            {
                strsel       = "select * from (select row_number() over (order by " + strOrderCondition + ") as rowno,p.*,o.orgName,case p.IsForbid when 1 then  '否' else '是'end as Forbid from " + strTableName + " and    p.PositionName like @PositionName and  o.orgName like @orgName) as result Where (rowno Between " + (anpager.CurrentPageIndex - 1) * anpager.PageSize + " and " + anpager.CurrentPageIndex * anpager.PageSize + ")";
                PositionName = "%" + PositionName + "%";
                OrgName      = "%" + OrgName + "%";
                SqlParameter[] parameters = { new SqlParameter("@PositionName", PositionName), new SqlParameter("@orgName", OrgName) };
                parameters[0].Value = PositionName;
                parameters[1].Value = OrgName;
                anpager.RecordCount = Convert.ToInt32(DbHelperSQL.GetSingle("Select Count(*) From " + strTableName + " and   p.PositionName like @PositionName and o.orgName like @orgName", parameters));
                dstTemp             = DbHelperSQL.Query(strsel, parameters);
            }



            if (dstTemp.Tables[0].Rows.Count == 0)
            {
                //DataRow dr = dstTemp.Tables[0].NewRow();
                //dstTemp.Tables[0].Rows.Add(dr);
                grvControl.DataSource = null;
                grvControl.DataBind();
            }
            else
            {
                grvControl.DataSource = dstTemp.Tables[0];
                grvControl.DataBind();
            }


            //动态设置用户自定义文本内容
            anpager.CustomInfoHTML  = "共有<font color=\"blue\"><b>" + anpager.RecordCount.ToString() + "</b></font>条记录";
            anpager.CustomInfoHTML += " 总页数:<font color=\"blue\"><b>" + anpager.PageCount.ToString() + "</b></font>页";
            anpager.CustomInfoHTML += " 当前页:第<font color=\"red\"><b>" + anpager.CurrentPageIndex.ToString() + "</b></font>页";
        }
        //#region Repeater控件分页帮定
        ///// <summary #region GridView控件分页帮定
        /// <summary>
        /// GridView控件分页帮定
        /// </summary>
        /// <param name="anpager">AspNetPager分页控件</param>
        /// <param name="strTableName">表名</param>
        /// <param name="strPrimaryKey">表的唯一主建名</param>
        /// <param name="strQuaryCondition">查询Where条件,不含Where</param>
        /// <param name="strOrderCondition">需要排序的字段名</param>
        /// <param name="rptControl">GridView控件</param>
        public static void GridViewPagerBind(Wuqi.Webdiyer.AspNetPager anpager, string strTableName, string strPrimaryKey, string strQuaryCondition, string strOrderCondition, System.Web.UI.WebControls.GridView grvControl)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@pageindex", SqlDbType.Int),
                new SqlParameter("@pagesize", SqlDbType.Int),
                new SqlParameter("@docount", SqlDbType.Bit),
                new SqlParameter("@strwhere", SqlDbType.NVarChar, 1000),
                new SqlParameter("@tablenm", SqlDbType.NVarChar, 100),
                new SqlParameter("@tbmainid", SqlDbType.NVarChar, 100),
                new SqlParameter("@strorder", SqlDbType.NVarChar, 100),
            };

            parameters[0].Value = anpager.CurrentPageIndex;
            parameters[1].Value = anpager.PageSize;
            parameters[2].Value = false;
            parameters[3].Value = strQuaryCondition;
            parameters[4].Value = strTableName;
            parameters[5].Value = strPrimaryKey;
            parameters[6].Value = strOrderCondition;

            if (strQuaryCondition == "")
            {
                anpager.RecordCount = Convert.ToInt32(DbHelperSQL.GetSingle("Select Count(*) From " + strTableName));
            }
            else
            {
                anpager.RecordCount = Convert.ToInt32(DbHelperSQL.GetSingle("Select Count(*) From " + strTableName + " Where " + strQuaryCondition));
            }
            DataSet dstTemp = DbHelperSQL.DRunProcedure("P_ControlPager", parameters, "NewTableName");

            if (dstTemp.Tables[0].Rows.Count == 0)
            {
                //DataRow dr = dstTemp.Tables[0].NewRow();
                //dstTemp.Tables[0].Rows.Add(dr);
                grvControl.DataSource = null;
                grvControl.DataBind();
            }
            else
            {
                grvControl.DataSource = dstTemp.Tables["NewTableName"];
                grvControl.DataBind();
            }


            //动态设置用户自定义文本内容
            anpager.CustomInfoHTML  = "共有<font color=\"blue\"><b>" + anpager.RecordCount.ToString() + "</b></font>条记录";
            anpager.CustomInfoHTML += " 总页数:<font color=\"blue\"><b>" + anpager.PageCount.ToString() + "</b></font>页";
            anpager.CustomInfoHTML += " 当前页:第<font color=\"red\"><b>" + anpager.CurrentPageIndex.ToString() + "</b></font>页";
        }
        protected void generatePDFButton_Click(object sender, EventArgs e)
        {
            DataTable aDataTable = aPatientManager.GetData(Convert.ToInt64(voterIdTextBox.Text));

            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.ShowHeaderWhenEmpty = true;
            GridView1.DataSource = aDataTable;
            GridView1.DataBind();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=AllHistoryOfAPatient.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter aStringWriter = new StringWriter();
            HtmlTextWriter aHtmlTextWriter = new HtmlTextWriter(aStringWriter);
            GridView1.RenderControl(aHtmlTextWriter);
            StringReader aStringReader = new StringReader(aStringWriter.ToString());
            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker aHtmlWorker = new HTMLWorker(pdfDocument);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);
            pdfDocument.Open();
            aHtmlWorker.Parse(aStringReader);
            pdfDocument.Close();
            Response.Write(pdfDocument);
            Response.End();
        }
Exemplo n.º 15
0
        /// <summary>
        ///     数组方式
        /// </summary>
        /// <param name="dataList"></param>
        /// <param name="fields"></param>
        /// <param name="headTexts"></param>
        /// <param name="title"></param>
        /// <param name="TableName"></param>
        public static void ExportToExcel(DataTable dataList, string[] fields, string[] headTexts, string title,
            string TableName) {
            var gvw = new GridView();
            int ColCount, i;
            //如果筛选的字段和对应的列头名称个数相对的情况下只导出指定的字段
            if (fields.Length != 0 && fields.Length == headTexts.Length) {
                ColCount = fields.Length;
                gvw.AutoGenerateColumns = false;

                for (i = 0; i < ColCount; i++) {
                    var bf = new BoundField();
                    bf.DataField = fields[i];
                    bf.HeaderText = headTexts[i];
                    gvw.Columns.Add(bf);
                }
            }
            else {
                gvw.AutoGenerateColumns = true;
            }
            gvw.DataSource = dataList;
            SetStype(gvw);
            //  gvw.Columns[]
            gvw.DataBind();
            ExportToExcel(gvw, title, TableName);
        }
        public async Task<FileResult> CreateSendExcellFile()
        {
            List<Report> report = await db.FilesDownloadNotes.Include(f => f.ApplicationUser).Include(f => f.FilesUploadNote)
                                         .Select(x => new Report
                                         {
                                             FileName = x.FilesUploadNote.Name,
                                             FileFileSize = x.FilesUploadNote.Size,
                                             FileType = x.FilesUploadNote.Type,
                                             DataUploaded = x.FilesUploadNote.DataTimeUpload,
                                             WhoUploaded = x.FilesUploadNote.UserName,
                                             TypeOperations = x.FileOperations,
                                             DataOperations = x.DateTimeDownload,
                                             WhoOperations = x.ApplicationUser.UserName
                                         }).ToListAsync();
 
            GridView grid = new GridView();
            grid.DataSource = report;
            grid.DataBind();
            StringWriter sw = new StringWriter(); 
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grid.RenderControl(htw);
            string r_name = "Report_" + DateTime.Now.ToString() + "_.xls";

            return File(Encoding.UTF8.GetBytes(sw.ToString()), "application/ms-excel", r_name);
        }
Exemplo n.º 17
0
        public void PositionsTest_Return_All_published_Postion_List()
        {
            //Arrange
            var myGridview = new System.Web.UI.WebControls.GridView();
            var parameter  = new ParametersForPositionList()
            {
                Operate      = "Page",
                UserID       = "mif",
                SchoolYear   = schoolyear,
                PositionType = "LTO",
                Panel        = "All",
                Status       = "Open",
                SearchBy     = "All",
                SearchValue1 = "",
                SearchValue2 = ""
            };
            string expect = "334";

            //Act
            List <PositionListPublish> publishList = PublishPositionExe.Positions(parameter);

            myGridview.AutoGenerateColumns = true;
            myGridview.DataSource          = publishList;
            myGridview.DataBind();

            var result = myGridview.Rows.Count.ToString();

            //Assert
            Assert.IsNotNull(result, $" Publish positions count is { result } ");
        }
        public ActionResult ViewHistory(HistoryInput historyInput)
        {
            if (ModelState.IsValid)
            {
                TimeSpan timeSpan = (historyInput.EndDate - historyInput.StartDate);
                if (timeSpan.Days >= 0)
                {
                    HistoryDAO History_DAO = new HistoryDAO();
                    List<History> HistoryList = History_DAO.ShowHisroty(historyInput.StartDate, historyInput.EndDate).ToList();

                    GridView gridView = new GridView();
                    gridView.DataSource = HistoryList;
                    gridView.DataBind();
                    Session["History"] = gridView;

                    return View(HistoryList);
                }
                else
                {
                    ModelState.AddModelError("", "Please Select a valid range with correct dates");
                    return View("ShowHistory");

                }
            }
            else
            {
                ModelState.AddModelError("", "History is not available");
                return View("ShowHistory");
            }
        }
Exemplo n.º 19
0
        public static void xlsport(GridView grd, string _fnm, Page p)
        {
            grd.Visible = true;
            gridstrip(grd);    
            grd.DataBind();

            HtmlForm form = new HtmlForm();
            string attachment = "attachment; filename=" + _fnm + csclass.ranfn() + ".xls";

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            p.EnableViewState = false;
            HttpContext.Current.Response.Charset = string.Empty;

            System.IO.StringWriter stw = new System.IO.StringWriter();
            HtmlTextWriter htextw = new HtmlTextWriter(stw);

            form.Controls.Add(grd);
            p.Controls.Add(form);

            form.RenderControl(htextw);
            HttpContext.Current.Response.Write(stw.ToString());
            HttpContext.Current.Response.End();
        }
 public GridView mostrar(GridView grv)
 {
     var consulta = from dato in db.Usuario select dato;
     grv.DataSource = consulta;
     grv.DataBind();
     return grv;
 }
Exemplo n.º 21
0
 private void dlstVote_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
 {
     if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem)
     {
         long     voteId   = System.Convert.ToInt64(this.dlstVote.DataKeys[e.Item.ItemIndex]);
         VoteInfo voteById = StoreHelper.GetVoteById(voteId);
         System.Collections.Generic.IList <VoteItemInfo> voteItems = StoreHelper.GetVoteItems(voteId);
         for (int i = 0; i < voteItems.Count; i++)
         {
             if (voteById.VoteCounts != 0)
             {
                 voteItems[i].Percentage = decimal.Parse((voteItems[i].ItemCount / voteById.VoteCounts * 100m).ToString("F", System.Globalization.CultureInfo.InvariantCulture));
             }
             else
             {
                 voteItems[i].Percentage = 0m;
             }
         }
         System.Web.UI.WebControls.GridView view = (System.Web.UI.WebControls.GridView)e.Item.FindControl("grdVoteItem");
         if (view != null)
         {
             view.DataSource = voteItems;
             view.DataBind();
         }
     }
 }
 public bool LlenarGrid_Web( GridView Generico )
 {
     if ( ! Validar() )
             return false;
         try
         {
             clsConexionBD objConexionBd = new clsConexionBD( strApp );
             objConexionBd.SQL = strSQL;
             if ( ! objConexionBd.LlenarDataSet( false ) )
             {
                 strError = objConexionBd.Error;
                 objConexionBd.CerrarCnx();
                 objConexionBd = null;
                 return false;
             }
             Generico.DataSource = objConexionBd.DataSet_Lleno.Tables[0];
             Generico.DataBind();
             objConexionBd.CerrarCnx();
             objConexionBd = null;
             return true;
         }
         catch (Exception ex)
         {
             strError = ex.Message;
             return false;
         }
 }
 public GridView ConsultaNombre(GridView grv, String valor)
 {
     var consulta = from dato in db.Usuario where dato.nombre == valor select dato;
     grv.DataSource = consulta;
     grv.DataBind();
     return grv;
 }
Exemplo n.º 24
0
        public void ExportRiskTableToXLS()
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = /*from d in dbContext.diners
                               * where d.user_diners.All(m => m.user_id == userID) && d.active == true */
                              from line in GlobalVariables.glob_risk_list
                              select new
            {
                RiskName        = line.risk_name,
                RiskCategory    = line.risk_category,
                RiskProbability = line.risk_probability,
                RiskImpact      = line.risk_impact,
                RiskRMMM        = line.risk_RMMM
            };

            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=RiskTable.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
        }
 /// <summary>
 /// 绑定数据到GridView,当表格数据为空时显示表头
 /// </summary>
 /// <param name="gridview"></param>
 /// <param name="table"></param>
 public static void GridViewDataBind(GridView gridview, DataTable table, string EmptyText = "No Data !")
 {
     //记录为空重新构造Gridview
     if (table.Rows.Count == 0)
     {
         table = table.Clone();
         table.Rows.Add(table.NewRow());
         gridview.DataSource = table;
         gridview.DataBind();
         int columnCount = table.Columns.Count;
         gridview.Rows[0].Cells.Clear();
         gridview.Rows[0].Cells.Add(new TableCell());
         gridview.Rows[0].Cells[0].ColumnSpan = columnCount;
         gridview.Rows[0].Cells[0].Text = EmptyText;
         gridview.Rows[0].Cells[0].Style.Add("text-align", "center");
     }
     else
     {
         //数据不为空直接绑定
         gridview.DataSource = table;
         gridview.DataBind();
     }
     //重新绑定取消选择
     gridview.SelectedIndex = -1;
 }
Exemplo n.º 26
0
        public bool LlenarGridWeb(System.Web.UI.WebControls.GridView grdGenerico)
        {
            if (strSQL == "")
            {
                strError = "Debe definir una instruccion SQL";
                return(false);
            }
            ClsConexion objConexionBD = new ClsConexion();

            if (strNombreTabla == "")
            {
                strNombreTabla = "DatosGridWeb";
            }
            if (objConexionBD.LlenarDataSet(strNombreTabla, strSQL, false))
            {
                grdGenerico.DataSource = objConexionBD.DataSet_Retornado.Tables[strNombreTabla];
                grdGenerico.DataBind();
                objConexionBD.CerrarConexion();
                objConexionBD = null;
                return(true);
            }
            else
            {
                strError = objConexionBD.Error;
                objConexionBD.CerrarConexion();
                objConexionBD = null;
                return(false);
            }
        }
        public void ExportClientsListToExcel()
        {
            var grid = new System.Web.UI.WebControls.GridView();
            string[] ClientsList={"mike","jonh","vladimit"};
            grid.DataSource = /*from d in dbContext.diners
                              where d.user_diners.All(m => m.user_id == userID) && d.active == true */
                              from d in ClientsList
                              select new
                              {
                                  FirstName = d
                              };

            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Exported_Diners.xls");
            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
        }
        public ActionResult ExportToExcel()
        {
            try
            {
                list = (List<NhanVien>)TempData["list"];
                if (list != null)
                {
                    GridView gv = new GridView();
                    gv.DataSource = list;
                    gv.DataBind();
                    Response.ClearContent();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition", "attachment; filename=DanhSachNhanVienVeHuu.xls");
                    Response.ContentType = "application/ms-excel";
                    Response.Charset = "";
                    StringWriter sw = new StringWriter();
                    HtmlTextWriter htw = new HtmlTextWriter(sw);
                    gv.RenderControl(htw);
                    Response.Output.Write(sw.ToString());
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    return Content("<script language='javascript' type='text/javascript'>alert('Không thể xuất file excel');");
                }

                return RedirectToAction("VeHuu");
            }
            catch (Exception)
            {

                throw;
            }
        }
        protected override void CreateChildControls()
        {
            //create new gridview object
            _gridView = new GridView
            {
                ID = string.Format("{0}_gridView", base.ID),
                AutoGenerateColumns = false
            };

            //Create Custom Field
            var customField = new TemplateField
            {
                HeaderTemplate = new SetTemplate(DataControlRowType.Header, "Name"),
                ItemTemplate = new SetTemplate(DataControlRowType.DataRow)
            };

            //Add custom field to gridview column
            _gridView.Columns.Add(customField);

            //Set test data list to datasource
            _gridView.DataSource = _list;

            //Bind gridview
            _gridView.DataBind();

            //Add gridview to composite control
            Controls.Add(_gridView);
        }
Exemplo n.º 30
0
 protected void ExportToPDF(DataTable table, string filename)
 {
     //Get the data from database into datatable
     //Create a dummy GridView
     GridView grdDownload = new GridView();
     grdDownload.AllowPaging = false;
     grdDownload.DataSource = table;
     grdDownload.DataBind();
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=" + filename);
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     StringWriter sw = new StringWriter();
     HtmlTextWriter hw = new HtmlTextWriter(sw);
     grdDownload.RenderControl(hw);
     StringReader sr = new StringReader(sw.ToString());
     StreamReader reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(sr.ReadToEnd().ToString())));
     Document pdfDoc = new Document(PageSize.A2);
     HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
     PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
     pdfDoc.Open();
     htmlparser.Parse(reader);
     pdfDoc.Close();
     Response.Write(pdfDoc);
     Response.End();
 }
Exemplo n.º 31
0
    public void exportToCSV <T>(string fileName, List <T> list, string CSVType)
    {
        if (list.Count == 0)
        {
            return;
        }

        StreamWriter sw = new StreamWriter(fileName, false);
        GridView     gv = new System.Web.UI.WebControls.GridView();

        gv.DataSource = list;
        gv.DataBind();

        // Header
        foreach (TableCell header in gv.HeaderRow.Cells)
        {
            sw.Write(header.Text); sw.Write(SEPARATOR);
        }

        // Content
        foreach (GridViewRow row in gv.Rows)
        {
            sw.Write(sw.NewLine);
            foreach (TableCell cell in row.Cells)
            {
                sw.Write(System.Net.WebUtility.HtmlDecode(cell.Text));
                sw.Write(SEPARATOR);
            }
        }
        sw.Close();
    }
Exemplo n.º 32
0
  /// <summary>Page Load.</summary>
  public void Page_Load
  (
   object     sender, 
   EventArgs  e
  ) 
  {
   String     exceptionMessage  =  null;
   DataSet    dataSet           =  null;
   Hashtable  userLogin         =  null;
   
   UtilityUser.UserLogin
   (
    ref userLogin,
    ref exceptionMessage
   );

   if ( exceptionMessage != null )
   {
    Response.Write( "Exception: " + exceptionMessage );
   	return;
   }	

   UtilityDatabase.DataSetFill
   (    
    ref userLogin,
    ref dataSet
   );
    
   GridViewUser.DataSource = dataSet;
   GridViewUser.DataBind();
  }//Page_Load
        public ActionResult GetUserExcelList(string searchType, string searchText, int? page, int? rows)
        {
            var grid = new System.Web.UI.WebControls.GridView();
            List<UserT> model = new UserBiz().GetUserList(searchType, searchText, page.Value, rows.Value);

            grid.DataSource = from m in model
                              select new
                              {
                                  LoginId = m.LoginId,
                                  LastLoginDate = m.LastLoginDate,
                                  IsDeleted = m.IsDeleted,
                                  DeletedDate = m.DeletedDate,
                                  InsertUser = m.InsertUser,
                                  InsertDate = m.InsertDate,

                              };

            grid.DataBind();

            Response.ClearContent();

            Response.AddHeader("content-disposition", string.Format("attachment; filename=Excel_{0}.xls", DateTime.Now.ToString("yyyyMMddhhmmss")));
            Response.Write("<meta http-equiv='Content-Type' content='text/html; charset=" + Request.ContentEncoding.HeaderName + "'>");
            Response.Buffer = true;

            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return View("Index");
        }
Exemplo n.º 34
0
        /// <summary>
        /// GridView导出到Excel
        /// </summary>
        /// <param name="gvBindData"></param>
        /// <param name="strExcelName">文件名</param>
        /// <param name="strCharset">编码类型</param>
        /// <param name="page">默认当前页面</param>
        public static void GridViewToExcel(GridView gvBindData, string strExcelName = "GridView", string strCharset = "GB2312", Page page = null)
        {
            gvBindData.AllowPaging = false;
            gvBindData.DataBind();
            for (int i = 0; i < gvBindData.Columns.Count; i++)
            {
                if (gvBindData.Columns[i].FooterText.IndexOf("Delete") >= 0)
                {
                    gvBindData.Columns[i].Visible = false;
                }
            }
            if (page == null)
            {
                page = ((Page)HttpContext.Current.Handler);
            }

            page.Response.Clear();
            page.Response.Buffer = false;
            page.Response.Charset = strCharset;
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strExcelName, Encoding.UTF8) + ".xls");
            page.Response.ContentEncoding = Encoding.GetEncoding(strCharset);
            page.Response.ContentType = "application/ms-excel";
            StringWriter oStringWriter = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(oStringWriter);
            gvBindData.RenderControl(writer);
            page.Response.Write(oStringWriter.ToString());
            page.Response.End();
            gvBindData.AllowPaging = true;
        }
Exemplo n.º 35
0
        public void Carrega(GridView grid, Int64 idDenuncia)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("   SELECT denuncias_msg.Data,");
            sql.Append("          denuncias_msg.UserName,");
            sql.Append("          denuncias_msg.Texto");
            sql.Append("     FROM denuncias_msg");
            sql.Append("    WHERE denuncias_msg.idDenuncia = @idDenuncia");
            sql.Append(" ORDER BY idMensagem");

            using (Banco banco = new Banco())
            {
                banco.AddParameter("idDenuncia", idDenuncia);

                using (MySqlDataReader reader = banco.ExecuteReader(sql.ToString(), 300))
                {
                    DataTable table = new DataTable("denuncias_msg");
                    table.Load(reader);

                    table.Columns[0].ColumnName = "Data";
                    table.Columns[1].ColumnName = "Usuário";
                    table.Columns[2].ColumnName = "Comentário";

                    grid.DataSource = table;
                    grid.DataBind();
                }

                Notificacoes notificacao = new Notificacoes();
                notificacao.ApagaNotificacoes(banco, idDenuncia, System.Web.HttpContext.Current.User.Identity.Name);
            }
        }
Exemplo n.º 36
0
        protected void generaXLS(string reporte, string campos, string sql)
        {
            GridView GridView2 = new GridView();
            GridView2.AllowPaging = false;
            GridView2.DataSource = obtienDatosTabla(campos, sql);
            GridView2.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + reporte + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; (i
                        <= (GridView2.Rows.Count - 1)); i++)
            {
                // Apply text style to each Row
                GridView2.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView2.RenderControl(hw);
            string style = "<style> .textmode{mso-number-format:\\@;}</style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
Exemplo n.º 37
0
        public void PositionTest_return_publishPosition_by_giving_PositionID()
        {
            //Arrange
            var myGridview = new System.Web.UI.WebControls.GridView();
            var parameter  = new ParametersForPosition()
            {
                SchoolYear = schoolyear,
                PositionID = getNewPublishID("LTO").ToString()
            };
            string expect = parameter.PositionID;

            //Act
            List <PositionPublish> publishList = PublishPositionExe.Position(parameter);

            myGridview.AutoGenerateColumns = true;
            myGridview.DataSource          = publishList;
            myGridview.DataBind();

            myGridview.SelectedIndex = 0;

            GridViewRow row = myGridview.SelectedRow;

            string result = row.Cells[14].Text; // PositionID in Gridview Cell position

            var result2 = publishList[0].PositionID;

            //Assert
            Assert.AreEqual(expect, result, $" Publish positions ID is { result } ");
        }
Exemplo n.º 38
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PerformanceTest pt = new PerformanceTest();
            pt.SetCount(1000);
            using (SqlSugarClient db = new SqlSugarClient(System.Configuration.ConfigurationManager.ConnectionStrings["sqlConn"].ToString()))
            {


                //ado.GetDataTable
                pt.Execute(i =>
                {
                    db.GetDataTable(@"select * from dbo.Student s inner join dbo.School sc on sc.id=s.sch_id 
left join dbo.Subject sb on sb.sid=s.id");

                }, m => { }, "ado.DateTable 纯SQL写法");


                //dapper
                var conn = db.GetConnection();
                pt.Execute(i =>
                {
                    conn.Query<Models.Student>(@"select * from dbo.Student s inner join dbo.School sc on sc.id=s.sch_id 
left join dbo.Subject sb on sb.sid=s.id").ToList();

                }, m => { }, "dapper 纯SQL写法");

                //sqlSugar
                pt.Execute(i =>
                {
                    db.Sqlable().Form("Student", "s")
                        .Join("School","sc","sc.id","s.sch_id",JoinType.INNER)
                        .Join("subject","sb","sb.sid","s.id",JoinType.LEFT).SelectToList<Models.Student>("*");

                }, m => { }, "sqlSugar SQL语法糖");
                //sqlSugar
                pt.Execute(i =>
                {
                    db.SqlQuery<Models.Student>(@"select * from dbo.Student s inner join dbo.School sc on sc.id=s.sch_id 
left join dbo.Subject sb on sb.sid=s.id").ToList();

                }, m => { }, "sqlSugar 纯SQL写法");


            }

            using (WebTest.TestLib.SqlSugarTestEntities db = new TestLib.SqlSugarTestEntities())
            {
                //EF
                pt.Execute(i =>
                {
                    db.ExecuteStoreQuery<WebTest.TestLib.Student>(@"select * from dbo.Student s inner join dbo.School sc on sc.id=s.sch_id 
left join dbo.Subject sb on sb.sid=s.id");

                }, m => { }, "EF4.0+sql05 纯SQL写法");
            }
            GridView gv = new GridView();
            gv.DataSource = pt.GetChartSource();
            gv.DataBind();
            Form.Controls.Add(gv);
        }
Exemplo n.º 39
0
        public string WS_loggerhistorial(System.Web.UI.WebControls.GridView grillaa)
        {
            //DELCARAR VARIABLES
            string email = "*****@*****.**";
            string msg   = null;

            //INSTANCIAR WS
            WS_LoggerService.LoggerServiceClient ws = new WS_LoggerService.LoggerServiceClient();
            ws.ClientCredentials.UserName.UserName = "******";
            ws.ClientCredentials.UserName.Password = "******";



            //ENVIO DE VARIABLES A WS Y OBTENEMOS DATASET PARA BINDEARLO EN GRIDVIEW
            try
            {
                ws.Open();
                grillaa.DataSource = ws.Historial(email);
                grillaa.DataBind();
                ws.Close();

                msg += "ws log consumido correctamente";
            }
            catch (Exception exc)
            {
                msg += exc.Message;
            }

            //REGRESAMOS RESPUESTA
            return(msg);
        }
Exemplo n.º 40
0
 internal static void Show(GridView ListTests, string UserName)
 {
     SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
     string str = "select d.Discipline_name, c.categories_name, t.name, ct.points, ct.dateComplite " +
         " from Complite_test as ct inner join test as t on ct.test_id = t.test_id " +
         " inner join Categories as c on c.cat_id = t.cat_id " +
         " inner join discipline as d on d.discipline_id = c.discipline_id " +
         " inner join users as u on u.user_id = ct.user_id where u.login = @login";
     SqlCommand cmd = new SqlCommand(str, con);
     cmd.Parameters.AddWithValue("login", UserName);
     try
     {
         con.Open();
         SqlDataSource ds = new SqlDataSource(con.ConnectionString, str);
         Parameter p = new Parameter("login", System.Data.DbType.String, UserName);
         ds.SelectParameters.Add(p);
         ListTests.DataSource = ds;
         ListTests.DataBind();
     }
     catch (Exception)
     {
         throw new ApplicationException("Не удается отобразить список завершенных тестов");
     }
     finally {
         con.Close();
     }
 }
Exemplo n.º 41
0
 private void BindItemData(GridView itemsview, int TopicID)
 {
     DataTable table = (DataTable) this.ViewState["dtcount"];
     DataRow[] rowArray = table.Select("TopicID=" + TopicID);
     object obj2 = table.Compute("sum(SubmitNum)", "TopicID=" + TopicID);
     int num = 0;
     if (obj2.ToString() != "")
     {
         num = int.Parse(obj2.ToString());
     }
     ArrayList list = new ArrayList();
     for (int i = 0; i < rowArray.Length; i++)
     {
         string str = rowArray[i]["Name"].ToString();
         int num3 = int.Parse(rowArray[i]["SubmitNum"].ToString());
         OptionList list2 = new OptionList {
             name = str,
             count = num3.ToString(),
             totalcount = num.ToString()
         };
         list.Add(list2);
     }
     itemsview.DataSource = list;
     itemsview.DataBind();
 }
Exemplo n.º 42
0
    public static void LoadCallLogPage(string search_val, System.Web.UI.WebControls.GridView gv, System.Web.UI.WebControls.Repeater rptPager, int pageIndex, DropDownList ddlPageSize, Label lbltotalrecord, int LocationID, DateTime FromDate, DateTime ToDate, String UserID, string SignUp)
    {
        int recordCount = 0;
        int PageSize    = int.Parse(ddlPageSize.SelectedValue);
        SqlClientProvider sqlClientProvider = new SqlClientProvider();
        DataSet           ds = sqlClientProvider.GetCallLogPageWise(search_val, pageIndex, PageSize, out recordCount, LocationID, FromDate, ToDate, UserID, SignUp);

        gv.DataSource = ds;
        gv.DataBind();

        string htmlStatus = "";

        foreach (DataRow dr in ds.Tables[1].Rows)
        {
            htmlStatus += dr["TourStatusName"].ToString() + " : (<b>";
            int count = 0;
            foreach (DataRow drCount in ds.Tables[2].Rows)
            {
                if (drCount["StastusID"].ToString() == dr["TourStatusID"].ToString())
                {
                    count = int.Parse(drCount["NoOfRecords"].ToString());
                }
            }

            htmlStatus += count.ToString() + "</b>) ";
        }

        lbltotalrecord.Text = htmlStatus + " Total Record Found : (<b>" + recordCount + "</b>)";
        clientsPaggination(rptPager, recordCount, pageIndex, PageSize);
    }
Exemplo n.º 43
0
        protected void btnDownload_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();

            Response.AddHeader("content-disposition", "attachment; filename=Baogia.xls");

            Response.Charset = "";

            Response.ContentType = "application/vnd.xls";

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter htmlWrite =
            new HtmlTextWriter(stringWrite);

            DataSet dts = new DataSet();
            SqlDataAdapter adt = new SqlDataAdapter();
            SqlCommand comm = new SqlCommand("Export_to_Excel", objConn.SqlConn());
            comm.CommandType = CommandType.StoredProcedure;
            comm.Connection.Open();
            adt.SelectCommand = comm;
            adt.Fill(dts);

            GridView g = new GridView();
            g.DataSource = dts;
            g.DataBind();

            g.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());

            Response.End();
        }
        protected void ExportToPDF(DataTable dt)
        {
            GridView gvExport = new GridView();
            gvExport.AllowPaging = false;
            gvExport.DataSource = dt;
            gvExport.DataBind();

            gvExport.HeaderRow.Style.Add("font-size", "10px");
            gvExport.HeaderRow.Style.Add("font-weight", "bold");
            gvExport.Style.Add("text-decoration", "none");
            gvExport.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            gvExport.Style.Add("font-size", "8px");

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=LinkSpace.pdf");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            gvExport.RenderControl(hw);

            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
Exemplo n.º 45
0
        public void ExportToExcel(DataTable dataTable, HttpResponse response)
        {
            // Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; (i
                        <= (GridView1.Rows.Count - 1)); i++)
            {
                // Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView1.RenderControl(hw);
            // style to format numbers to string
            string style = "<style> .textmode{mso-number-format:\\@;}</style>";
            response.Write(style);
            response.Output.Write(sw.ToString());
            response.Flush();
            response.End();
        }
Exemplo n.º 46
0
        public bool ToExcel(HttpResponseBase Response, DataTable listTable, string nomeArquivo = "ConsultaPedidos.xls", int columnsMerged = 0)
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = listTable;


            grid.DataBind();

            if (columnsMerged > 0)
            {
                MergeRows(grid, columnsMerged);
            }


            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + nomeArquivo);
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return(true);
        }
        public ActionResult ViewCards(CardInput cardInput)
        {
            if (ModelState.IsValid)
            {
                CardGenerator cardGenerator = new CardGenerator(cardInput.GeneratingDate, cardInput.NumberOfCards);
                List<Card> CardList = cardGenerator.GetCardsList();
                CardDAO cardDAO = new CardDAO();
                if (!cardDAO.ISExsistCardDate(CardList[0].CardNumber))
                {
                    GridView gridView = new GridView();
                    gridView.DataSource = CardList;
                    gridView.DataBind();
                    Session["CardsListEXCEL"] = gridView;
                    Session["CardsList"] = CardList;

                    return View(CardList);
                }
                else
                {
                    ModelState.AddModelError("", "You have already generated cards on this date, so choose aonther date. ");
                    return View("ShowCards");

                }

            }
            else
            {
                ModelState.AddModelError("", "Card List is not available");
                return View("ShowCards");
            }
        }
Exemplo n.º 48
0
        public ActionResult ExportProductData()
        {
            // string ss = "<table><td><td></table>";
               var products = Session["Product"];
               GridView gv = new GridView();
               gv.DataSource = products;
               gv.DataBind();
               Response.ClearContent();
               Response.Buffer = true;
               Response.AddHeader("content-disposition", "attachment; filename=Orderlist.xls");
               Response.ContentType = "application/ms-excel";
               Response.Charset = "";
               StringWriter sw = new StringWriter();
               HtmlTextWriter htw = new HtmlTextWriter(sw);
               gv.RenderControl(htw);
               Response.Output.Write(sw.ToString());
               Response.Flush();
               Response.End();

               //Response.ClearContent();
               //Response.AddHeader("content-disposition", "attachment; filename=Orderlist.xls");
               //Response.ContentType = "application/ms-excel";
               //Response.Write(ss);
               //Response.End();

               return RedirectToAction("Reports");
        }
        public ActionResult ViewBalanceSheet(BalanceSheetInput balanceSheet)
        {
            if (ModelState.IsValid)
            {
                TimeSpan timeSpan = (balanceSheet.MonthEnd - balanceSheet.MonthStart);
                if (timeSpan.Days >= 0)
                {
                    BalanceSheetDAO BalanceSheetDAO = new BalanceSheetDAO();
                    List<BalanceSheet> BalanceSheetList = BalanceSheetDAO.GetMonthlyBaanceSheet(balanceSheet.MonthStart, balanceSheet.MonthEnd, balanceSheet.UnitPrice).ToList();

                    GridView gridView = new GridView();
                    gridView.DataSource = BalanceSheetList;
                    gridView.DataBind();
                    Session["BalanceSheet"] = gridView;

                    return View(BalanceSheetList);
                }
                else
                {
                    ModelState.AddModelError("", "Please Select a valid range with correct dates");
                    return View("ShowBalanceSheet");
                }
            }
            else
            {
                ModelState.AddModelError("", "Balance Sheet is not available");
                return View("ShowBalanceSheet");

            }
        }
  }//Page_Load

  /// <summary>PageRefresh().</summary>
  public void PageRefresh()
  {

   DataSet[]  dataSetMultiple       =  (DataSet[]) Session["dataSetMultiple"];

   Contact contact = (Contact) Session["contact"];
   
   SequenceOrderId = contact.SequenceOrderId;
   FirstName = contact.FirstName;
   LastName = contact.LastName;
   OtherName = contact.OtherName;
   Company = contact.Company;
   Prefix = contact.Prefix;
   Suffix = contact.Suffix;
   Commentary = contact.Commentary;
   ScriptureReference = contact.ScriptureReference;
   
   GridViewContactEmail.DataSource  =  dataSetMultiple[0];
   GridViewContactEmail.DataBind();

   GridViewContactURI.DataSource    =  dataSetMultiple[1];
   GridViewContactURI.DataBind();

   GridViewTelephone.DataSource     =  dataSetMultiple[2];
   GridViewTelephone.DataBind();

   GridViewStreetAddress.DataSource =  dataSetMultiple[3];
   GridViewStreetAddress.DataBind();
   
   Feedback = null;
  }  	
Exemplo n.º 51
0
        public void ExportClientsListToExcel()
        {
            var grid = new System.Web.UI.WebControls.GridView();

            string[] ClientsList = { "mike", "jonh", "vladimit" };
            grid.DataSource = /*from d in dbContext.diners
                               * where d.user_diners.All(m => m.user_id == userID) && d.active == true */
                              from d in ClientsList
                              select new
            {
                FirstName = d
            };

            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Exported_Diners.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
        }
Exemplo n.º 52
0
        public ActionResult ExportToPdf()
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = GetAirtelDetails();
            grid.DataBind();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=MyPdf.pdf");
            Response.ContentType = "application/pdf";

            Response.Charset = "";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            StringReader sr         = new StringReader(sw.ToString());
            Document     pdfDoc     = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker   htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);

            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return(View("Index"));
        }
Exemplo n.º 53
0
 public void BuscarPublicacion(GridView GridView1, string SearchWord, int id_usr)
 {
     String strConnString = ConfigurationManager.ConnectionStrings["ConexionRedSocial"].ConnectionString;
     SqlConnection con = new SqlConnection(strConnString);
     SqlCommand cmd = new SqlCommand();
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.CommandText = "BuscarPublicacion";
     cmd.Parameters.Add("@id_usr", SqlDbType.Int).Value = id_usr;
     cmd.Parameters.Add("@SearchWord", SqlDbType.Text).Value = SearchWord.Trim();
     cmd.Connection = con;
     try
     {
         con.Open();
         GridView1.EmptyDataText = "No hay productos publicados que se ajusten a tu busqueda. Intentá de nuevo.";
         GridView1.DataSource = cmd.ExecuteReader();
         GridView1.DataBind();
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         con.Close();
         con.Dispose();
     }
 }
    protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dtChildTable = GetChildTableData();
            // List<Skills> objChildTable = GetChildTableData();
            DataTable dtCloneChildTable = dtChildTable.Clone();
            Image     img = (Image)e.Row.Cells[0].FindControl("img1");

            Literal ltrl = (Literal)e.Row.FindControl("lit1");
            ltrl.Text = ltrl.Text.Replace("trCollapseGrid", "trCollapseGrid" + e.Row.RowIndex.ToString());
            string str = "trCollapseGrid" + e.Row.RowIndex.ToString();
            e.Row.Cells[0].Attributes.Add("OnClick", "OpenTable('" + str + "','" + img.ClientID + "')");
            e.Row.Cells[0].RowSpan = 1;
            System.Web.UI.WebControls.GridView gvChild = (System.Web.UI.WebControls.GridView)e.Row.FindControl("gvChild");

            DataRow[] gvChildRows = dtChildTable.Select("EmployeeId = " + e.Row.Cells[1].Text);
            foreach (DataRow gvChildRow in gvChildRows)
            {
                dtCloneChildTable.ImportRow(gvChildRow);
            }
            gvChild.DataSource = dtCloneChildTable;
            gvChild.DataBind();
        }
    }
Exemplo n.º 55
0
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            //Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = BindGridView();
            GridView1.DataBind();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename=" + DateTime.Now.Year + "-Newly_Hired" + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                //Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }
            GridView1.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
Exemplo n.º 56
0
        /// <summary>
        /// 将DataTable数据导出到EXCEL,调用该方法后自动返回可下载的文件流
        /// </summary>
        /// <param name="dtData">要导出的数据源</param>
        public static void DataTable1Excel(System.Data.DataTable dtData, string name)
        {
            System.Web.UI.WebControls.GridView gvExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, Encoding.UTF8).ToString());
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                curContext.Response.Charset         = "utf-8";

                // 导出excel文件
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                // 为了解决gvData中可能进行了分页的情况,需要重新定义一个无分页的GridView
                gvExport             = new System.Web.UI.WebControls.GridView();
                gvExport.DataSource  = dtData.DefaultView;
                gvExport.AllowPaging = false;

                gvExport.DataBind();

                // 返回客户端
                gvExport.RenderControl(htmlWriter);
                curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />" + strWriter.ToString());
                curContext.Response.End();
            }
        }
Exemplo n.º 57
0
    /// <summary>
    /// dtData是要导出为Excel的DataTable,FileName是要导出的Excel文件名(不加.xls)
    /// </summary>
    /// <param name="dtData"></param>
    /// <param name="FileName"></param>
    private void DataTable2Excel(DataTable dtData, String FileName)
    {
        System.Web.UI.WebControls.GridView dgExport = null;
        //当前对话
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        //IO用于导出并返回excel文件
        System.IO.StringWriter       strWriter  = null;
        System.Web.UI.HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            //设置编码和附件格式
            //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            curContext.Response.ContentType     = "application nd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            curContext.Response.Charset         = "GB2312";

            //导出Excel文件
            strWriter  = new System.IO.StringWriter();
            htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
            dgExport             = new System.Web.UI.WebControls.GridView();
            dgExport.DataSource  = dtData.DefaultView;
            dgExport.AllowPaging = false;
            dgExport.DataBind();

            //下载到客户端
            dgExport.RenderControl(htmlWriter);
            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }
    }
        protected void ChecklistRulesInformationEmptyFix(GridView grdChecklistRulesInformation)
        {
            if (grdChecklistRulesInformation.Rows.Count == 0)
            {
                DateTime lastService = new DateTime();
                DateTime nextDue = new DateTime();
                UnitInformationTDS.ChecklistDetailsDataTable dt = new UnitInformationTDS.ChecklistDetailsDataTable();
                dt.AddChecklistDetailsRow(0, "", "", lastService, nextDue, false, "Unknown", false);
                Session["unitsChecklistRulesEditDummy"] = dt;

                grdChecklistRulesInformation.DataBind();
            }

            // normally executes at all postbacks
            if (grdChecklistRulesInformation.Rows.Count == 1)
            {
                UnitInformationTDS.ChecklistDetailsDataTable dt = (UnitInformationTDS.ChecklistDetailsDataTable)Session["unitsChecklistRulesEditDummy"];
                if (dt != null)
                {
                    // hide row
                    grdChecklistRulesInformation.Rows[0].Visible = false;
                    grdChecklistRulesInformation.Rows[0].Controls.Clear();
                }
            }
        }
        private void BindGridFactura(Int32 currentPage)
        {
            DsImportesVentas ds = null;

            // configuro la grilla
            SisPackController.AdministrarGrillas.Configurar(gridFacturasConceptos, this.CantidadOpciones);
            gridFacturasConceptos.ShowFooter  = true;
            gridFacturasConceptos.AllowPaging = true;

            if (ddlGridFacturasAgrupadoPor.SelectedValue == "0")
            {
                gridFacturasConceptos.Columns[0].HeaderText = "Agencia";
            }
            else if (ddlGridFacturasAgrupadoPor.SelectedValue == "1")
            {
                gridFacturasConceptos.Columns[0].HeaderText = "Concepto de facturación";
            }
            else
            {
                gridFacturasConceptos.Columns[0].HeaderText = "";
            }

            // Reviso si los datos están en memoria
            if (Session["DsImportesVentas_FacturasConceptos"] == null)
            {
                // Los datos no están en memoria. Los busco
                IConsultasVentas consulta = ConsultasVentasFactory.GetConsultasVentas();
                if (this.busqAgenciaOrigen.Sucursal != "" && this.busqAgenciaOrigen.RazonSocial != "" && this.busqAgenciaOrigen.AgenciaID != "" && this.ddlZonaOrigen.SelectedValue.ToString() == "0")
                {
                    consulta.AgenciaOrigenID = Convert.ToInt32(this.busqAgenciaOrigen.AgenciaID);
                }
                else
                {
                    consulta.AgenciaOrigenID = 0;
                    consulta.ZonaOrigenID    = Utiles.Validaciones.obtieneEntero(this.ddlZonaOrigen.SelectedValue.ToString());
                }


                consulta.ConceptoFacturacionID       = Utiles.Validaciones.obtieneEntero(ddlConceptoFacturacion.SelectedValue);
                consulta.FechaDesde                  = this.txtFechaDesde.Text != "" ? Utiles.Fechas.FormatFechaDDMMYYYY(this.txtFechaDesde.Text) : Utiles.Fechas.FormatFechaDDMMYYYY("01/01/1900");
                consulta.FechaHasta                  = this.txtFechaHasta.Text != "" ? Utiles.Fechas.FormatFechaDDMMYYYY(this.txtFechaHasta.Text) : DateTime.Today;
                consulta.AgrupacionFacturasConceptos = Convert.ToInt32(ddlGridFacturasAgrupadoPor.SelectedValue);
                consulta.CondicionPagoID             = Utiles.Validaciones.obtieneEntero(this.ddlCondicionPago.SelectedValue);
                ds = consulta.GetImportesFacturasConceptos();
                Session["DsImportesVentas_FacturasConceptos"] = ds;
            }
            else
            {
                // Los datos están en memoria
                ds = (DsImportesVentas)Session["DsImportesVentas_FacturasConceptos"];
            }

            // Cargo los datos
            gridFacturasConceptos.DataSource = ds.FacturasConceptos;
            gridFacturasConceptos.PageIndex  = currentPage;
            gridFacturasConceptos.DataBind();

            lblTituloGrillaGuias.Visible = true;
        }
Exemplo n.º 60
0
        /// <summary>
        /// 描述:把DataTable内容导出excel并返回客户端
        /// 作者:李伟波
        /// 时间:2012-10-18
        /// </summary>
        /// <param name="dtData"></param>
        /// <param name="header"></param>
        /// <param name="fileName"></param>
        /// <param name="mergeCellNums">要合并的列索引字典 格式:列索引-合并模式(合并模式 1 合并相同项、2 合并空项、3 合并相同项及空项)</param>
        /// <param name="mergeKey">作为合并项的标记列索引</param>
        public static void DataTable2Excel(System.Data.DataTable dtData, TableCell[] header, string fileName, Dictionary <int, int> mergeCellNums, int?mergeKey)
        {
            System.Web.UI.WebControls.GridView gvExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType     = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                curContext.Response.Charset         = "gb2312";
                if (!string.IsNullOrEmpty(fileName))
                {
                    //处理中文名乱码问题
                    fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                    curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + (fileName.ToLower().EndsWith(".xls") ? fileName : fileName + ".xls")));
                }
                // 导出excel文件
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 重新定义一个无分页的GridView
                gvExport             = new System.Web.UI.WebControls.GridView();
                gvExport.DataSource  = dtData.DefaultView;
                gvExport.AllowPaging = false;
                //优化导出数据显示,如身份证、12-1等显示异常问题
                gvExport.RowDataBound += new System.Web.UI.WebControls.GridViewRowEventHandler(dgExport_RowDataBound);

                gvExport.DataBind();
                //处理表头
                if (header != null && header.Length > 0)
                {
                    if (gvExport.HeaderRow == null)
                    {
                        return;
                    }
                    gvExport.HeaderRow.Cells.Clear();
                    gvExport.HeaderRow.Cells.AddRange(header);
                }
                //合并单元格
                if (mergeCellNums != null && mergeCellNums.Count > 0)
                {
                    foreach (int cellNum in mergeCellNums.Keys)
                    {
                        MergeRows(gvExport, cellNum, mergeCellNums[cellNum], mergeKey);
                    }
                }

                // 返回客户端
                gvExport.RenderControl(htmlWriter);
                curContext.Response.Clear();
                curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString());
                curContext.Response.End();
            }
        }