Asp. NET format DataGrid Example

Source: Internet
Author: User
Tags format datagrid example eval net return sort version visual studio
Asp.net|datagrid

The following code implements the column that formats the DataGrid, which is the function of converting the 0,1 value in the data source to the actual text, primarily in the case of data binding.

View examples

First prepare the data source, the data source uses the database, the XML, the array and so on all May. The following is an example of XML. Contacts.xml files are as follows:

<?xml version= "1.0" encoding= "gb2312" standalone= "yes"?>
<Contacts>
<Contact>
<Email>myaddress@mycompany.com</Email>
<firstname>e Chapter </FirstName>
<LastName> Mencius </LastName>
<Manager>0</Manager>
</Contact>
<Contact>
<Email>youraddress@yourcompany.com</Email>
<FirstName> Constitutional Council </FirstName>
<LastName> Meng </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 Developer Corner </FirstName>
<LastName/>
<Manager>0</Manager>
</Contact>
<Contact>
<Email>hhh@hhh.hh</Email>
<firstname>xml Developer Corner </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" &GT;WEB&LT;/A&GT;. 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 > ">
<meta name= "vs_defaultClientScript" content= "<a href=" http://dev.21tx.com/web/javascript/"target=" >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%" >
<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" >
<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 the code generated by the Web Forms Designer
' This call is required by the Web Forms Designer.
<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: This method call is required by the Web Forms Designer
' Do not modify it using the Code Editor.
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 = "Example of a formatted DataGrid" Converts the 0,1 value in the data source to the actual text ""
Formatdatagrid.columns (0). HeaderText = "Name"
Formatdatagrid.columns (1). HeaderText = "E-mail"
Formatdatagrid.columns (2). HeaderText = "position"
' Load XML data original, note: This is not related to the original type of data, but also applicable to the database
_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
' Data binding only when the page is first requested
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
' Format Name column
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

' Make sure you're dealing with data rows, not headers or footer.
If E.item.itemtype = ListItemType.Item OrElse e.item.itemtype = ListItemType.AlternatingItem Then
' Get the value of the manager field
Dim Ismanager As String = CType (DataBinder.Eval (e.Item.DataItem, "Manager"), String)

If Ismanager = "1" Then
' Set text and background colors
E.item.cells (2). Text = "Manager"
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 = "Ordinary Employee"
End If
End If
End Sub
End Class

C # version

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 the call are required by the ASP.net Web Form Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Required to Designer support-do not modify
The contents is 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)
{
Load XML Data Original, note: This is not related to the original type of data, but also applicable to the database
_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)
{
Format Name column
Return (String) LastName + "," + (string) FirstName;
}

protected void Formatdatagrid_itemdatabound (object source,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
Make sure that you are working with data rows, not headers or footer
if (E.item.itemtype = = ListItemType.Item | | e.item.itemtype = = listitemtype.alternatingitem)
{
Get the value of the manager field
String Ismanager = (string) DataBinder.Eval (e.Item.DataItem, "Manager");

if (Ismanager = = "1")
{
' Set text and background colors
E.ITEM.CELLS[2]. Text = "Manager"
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 = "Ordinary Employees";
}
}
}
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.