ASP.NET格式化DataGrid的例子

來源:互聯網
上載者:User
asp.net|datagrid

    下面的代碼實現格式化DataGrid的列,也即是將資料原中的0,1值轉換成實際的文字的功能,主要是在資料繫結的幫定事件。
  
  查看例子
  
  首先準備資料來源,資料來源採用資料庫、XML、數組等都可以。下面以XML做例子。Contacts.xml檔案如下:
  
  <?xml version="1.0" encoding="gb2312" standalone="yes"?>
  <Contacts>
   <Contact>
   <Email>myaddress@mycompany.com</Email>
   <FirstName>E章</FirstName>
   <LastName>孟子</LastName>
   <Manager>0</Manager>
   </Contact>
   <Contact>
   <Email>youraddress@yourcompany.com</Email>
   <FirstName>憲會</FirstName>
   <LastName>孟</LastName>
   <Manager>1</Manager>
   </Contact>
   <Contact>
   <Email>mm@mmm.mm</Email>
   <FirstName>Lover</FirstName>
   <LastName>Net</LastName>
   <Manager>0</Manager>
   </Contact>
   <Contact>
   <Email>xxx@xxxx.xx</Email>
   <FirstName>NET開發人員園地</FirstName>
   <LastName/>
   <Manager>0</Manager>
   </Contact>
   <Contact>
   <Email>hhh@hhh.hh</Email>
   <FirstName>XML開發人員園地</FirstName>
   <LastName/>
   <Manager>1</Manager>
   </Contact>
  </Contacts>
  
  
  FormatDataGridVB.ASPx
  
  <%@ Page Language="vb" AutoEventWireup="false" Codebehind="FormatDataGridVB.aspx.vb"
   Inherits="aspx<a href="http://dev.21tx.com/web/" target="_blank">Web</a>.FormatDataGridVB" %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
  <HTML>
   <HEAD>
   <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
   <meta name="CODE_LANGUAGE" Content="<a href="http://dev.21tx.com/dotnet/csharp/" target="_blank">C#</a>">
   <meta name="vs_defaultClientScript" content="<a href="http://dev.21tx.com/web/javascript/" target="_blank">JavaScript</a>">
   <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
   </HEAD>
   <body>
   <form id="idbSample" method="post" runat="server" class="SubHeading">
   <asp:Label ID="MyTitle" runat="server" Font-Bold="True"></asp:Label>
   <br>
   <br>
   <asp:DataGrid id="FormatDataGrid" runat="server" AutoGenerateColumns="False" Width="100%">
   <HeaderStyle Font-Bold="True"></HeaderStyle>
   <Columns>
   <asp:TemplateColumn>
   <ItemTemplate>
   <asp:Label
   Text='<%# FormatFullName(DataBinder.Eval(Container, "DataItem.FirstName"),_
   DataBinder.Eval(Container, "DataItem.LastName")) %>'
   runat="server" ID="Label1">
   </asp:Label>
   </ItemTemplate>
   </asp:TemplateColumn>
   <asp:BoundColumn DataField="Email" ReadOnly="True"></asp:BoundColumn>
   <asp:BoundColumn DataField="Manager" ReadOnly="True">
   <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
   <ItemStyle HorizontalAlign="Center"></ItemStyle>
   </asp:BoundColumn>
   </Columns>
   </asp:DataGrid>
   </form>
   </body>
  </HTML>

   FormatDataGridVB.aspx.vb
  
  Imports System
  Imports System.Data
  Imports System.Web.UI
  Imports System.Web.UI.WebControls
  Imports System.Xml
  
  Public Class FormatDataGridVB
   Inherits System.Web.UI.Page
   Protected WithEvents FormatDataGrid As System.Web.UI.WebControls.DataGrid
   Protected WithEvents MyTitle As System.Web.UI.WebControls.Label
  
  #Region " Web Form設計器產生的程式碼 "
   '該調用是 Web Form設計器所必需的。
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  
   End Sub
  
   Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
   'CODEGEN: 此方法調用是 Web Form設計器所必需的
   '不要使用代碼編輯器修改它。
   InitializeComponent()
   End Sub
  
  #End Region
  
   Private _dsContacts As DataSet
  
   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   MyTitle.Text = "格式化DataGrid的例子【將資料原中的0,1值轉換成實際的文字】"
   FormatDataGrid.Columns(0).HeaderText = "姓名"
   FormatDataGrid.Columns(1).HeaderText = "電子郵件"
   FormatDataGrid.Columns(2).HeaderText = "職位"
   ' 裝載XML資料原,注意:這裡與資料原類型沒有關係,換成資料庫也是適用的
   _dsContacts = New DataSet()
   _dsContacts.ReadXml(Server.MapPath("Contacts.xml"))
   Dim dcPk As DataColumn() = {_dsContacts.Tables("Contact").Columns("Email")}
   _dsContacts.Tables("Contact").PrimaryKey = dcPk
  
   If Not Page.IsPostBack Then
   ' 只在頁面首次請求時才進行資料繫結
   BindContacts()
   End If
   End Sub
  
   Private Sub BindContacts()
   Dim dv As DataView = New DataView(_dsContacts.Tables("Contact"))
   dv.Sort = "LastName, FirstName"
   FormatDataGrid.DataSource = dv
   FormatDataGrid.DataBind()
   End Sub
  
   Protected Function FormatFullName(ByVal FirstName As Object, ByVal LastName As Object) As String
   ' 格式劃名稱列
   Return CType(LastName, String) & "." & CType(FirstName, String)
   End Function
  
   Private Sub FormatDataGrid_ItemDataBound(ByVal sender As Object,_
   ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles FormatDataGrid.ItemDataBound
  
   ' 確保處理的是資料行,而不是Header或者Footer
   If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
   ' 得到Manager欄位的值
   Dim isManager As String = CType(DataBinder.Eval(e.Item.DataItem, "Manager"), String)
  
   If isManager = "1" Then
   ' 設定文字和背景顏色
   e.Item.Cells(2).Text = "經理"
   e.Item.Cells(2).Style.Add("font-weight", "bold")
   e.Item.Cells(2).ForeColor = System.Drawing.Color.Red
   e.Item.BackColor = System.Drawing.Color.AliceBlue
   Else
   e.Item.Cells(2).Text = "普通員工"
   End If
   End If
   End Sub
  End Class
  
  C#版本
  
  using System;
  using System.Collections;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;
  
   /// <summary>
   /// Summary description for idbSample.
   /// </summary>
   public class idbSample : System.Web.UI.Page
   {
  
   #region Web Form Designer generated code
   override protected void OnInit(EventArgs e)
   {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
   }
  
   /// <summary>
   /// Required method for Designer support - do not modify
   /// the contents of this method with the code editor.
   /// </summary>
   private void InitializeComponent()
   {
   this.dgContacts.ItemDataBound +=
   new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgContacts_ItemDataBound);
   this.Load += new System.EventHandler(this.Page_Load);
  
   }
   #endregion
  
   protected System.Web.UI.WebControls.DataGrid FormatDataGrid;
  
   private DataSet _dsContacts;
  
   private void Page_Load(object sender, System.EventArgs e)
   {
   // 裝載XML資料原,注意:這裡與資料原類型沒有關係,換成資料庫也是適用的
   _dsContacts = new DataSet();
   _dsContacts.ReadXml(Server.MapPath("Contacts.xml"));
   DataColumn[] dcPk = {_dsContacts.Tables["Contact"].Columns["Email"]};
   _dsContacts.Tables["Contact"].PrimaryKey = dcPk;
  
   if (!Page.IsPostBack )
   {
   BindContacts();
   }
   }
  
   private void BindContacts()
   {
   DataView dv = new DataView(_dsContacts.Tables["Contact"]);
   dv.Sort = "LastName, FirstName";
   dgContacts.DataSource = dv;
   dgContacts.DataBind();
   }
  
   protected string FormatFullName(object FirstName, object LastName)
   {
   // 格式劃名稱列
   return (string)LastName + ", " + (string)FirstName;
   }
  
   protected void FormatDataGrid_ItemDataBound(object source,
   System.Web.UI.WebControls.DataGridItemEventArgs e)
   {
   // 確保處理的是資料行,而不是Header或者Footer
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
   // 得到Manager欄位的值
   string isManager = (string)DataBinder.Eval(e.Item.DataItem, "Manager");
  
   if (isManager == "1")
   {
   // ' 設定文字和背景顏色
   e.Item.Cells[2].Text = "經理"
   e.Item.Cells[2].Style.Add("font-weight", "bold")
   e.Item.Cells[2].ForeColor = System.Drawing.Color.Red
   e.Item.BackColor = System.Drawing.Color.AliceBlue
   }
   else
   {
   e.Item.Cells[2].Text = "普通員工";
   }
   }
   }
   }



相關文章

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。