当前位置: 首页>>代码示例>>C#>>正文


C# GridView.DataBind方法代码示例

本文整理汇总了C#中System.Web.UI.WebControls.GridView.DataBind方法的典型用法代码示例。如果您正苦于以下问题:C# GridView.DataBind方法的具体用法?C# GridView.DataBind怎么用?C# GridView.DataBind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.UI.WebControls.GridView的用法示例。


在下文中一共展示了GridView.DataBind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ShowGridAlways

        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();
            }
        }
开发者ID:thaond,项目名称:vdms-sym-project,代码行数:29,代码来源:WebUtils.cs

示例2: ExportToExcel

        /// <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);
        }
开发者ID:kangwl,项目名称:DotNet.Mix,代码行数:33,代码来源:ExcelExport.cs

示例3: ChecklistRulesInformationEmptyFix

        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();
                }
            }
        }
开发者ID:NosDeployer,项目名称:TestBranching,代码行数:25,代码来源:units_checklist_rules.aspx.cs

示例4: BuscarPublicacion

 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();
     }
 }
开发者ID:LoPresto,项目名称:ProyectoWeb,代码行数:27,代码来源:PublicacionesDA.cs

示例5: ViewCards

        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");
            }
        }
开发者ID:MisuBeImp,项目名称:DhakaUniversityCyberCenterAdministratorSite,代码行数:31,代码来源:CardController.cs

示例6: ExportToExcel

        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();
        }
开发者ID:rudolfcruz,项目名称:Reports,代码行数:29,代码来源:GenReportes.cs

示例7: btnDownload_Click

        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();
        }
开发者ID:phamtuanchip,项目名称:tmdt,代码行数:33,代码来源:Right.ascx.cs

示例8: CreateSendExcellFile

        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);
        }
开发者ID:Run-L,项目名称:FileTransferMonitor,代码行数:25,代码来源:FilesDownloadNotesController.cs

示例9: ConsultaNombre

 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;
 }
开发者ID:wgcv,项目名称:Ayudantias-Programacion-en-Capas,代码行数:7,代码来源:ClaseGeneral.cs

示例10: GridViewDataBind

 /// <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;
 }
开发者ID:ZhuangChen,项目名称:CSharpBasicTraining,代码行数:30,代码来源:07DataBinding.aspx.cs

示例11: GetUserExcelList

        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");
        }
开发者ID:ByunSeungHyun,项目名称:AssetManagementSystem,代码行数:34,代码来源:UserController.cs

示例12: LlenarGrid_Web

 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;
         }
 }
开发者ID:jdzapataduque,项目名称:Cursos-Capacitando,代码行数:27,代码来源:clsLlenarGrids.cs

示例13: generaXLS

        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();
        }
开发者ID:rudolfcruz,项目名称:Reports,代码行数:27,代码来源:frmGenRep.aspx.cs

示例14: Carrega

        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);
            }
        }
开发者ID:ops-org,项目名称:ops.net.br,代码行数:32,代码来源:Comentarios.cs

示例15: generatePDFButton_Click

        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();
        }
开发者ID:MirajHossain,项目名称:Community-Medicine-System,代码行数:26,代码来源:PatientHistoryUI.aspx.cs


注:本文中的System.Web.UI.WebControls.GridView.DataBind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。