DataGrid control
DataGrid control allows you to generate a list of rich data source format. In addition, it also supports selection items with other operations.
The four examples of this section use tables that include the title information (title, title ID, author, price and publishing date). All data is maintained with XML in Titlesdb.xml. When establishing a page to represent the content of this table and select books, these examples follow the incremental method. The code list contains the black body text to indicate the change made by a sample built in the previous example.
Test from titlesdb.xml:
<root>
<schema id = documentelement targetNamespace =
xmlns = http://www.w3.org/1999/xmlschema
xmlns: msdata = urn: schemaS-Microsoft-COM: XML-MSData>
<element name = table>
<Complextype Content = Elementsonly>
<element name = title_id type = string> </element>
<element name = title type = string> </element>
<element name = AU_NAME TYPE = String> </Element>
<element name = price msdata: datatype = system.currency
minoccurs = 0
Type = String> </Element>
<element name = pubdate type = timeInstant> </Element>
</Complextype>
<nique name = TitleConstraint MSData: Primarykey = True>
<selector>. </Selector>
<field> Title_id </field>
</unique>
</Element>
</schema>
<documentelement>
<Title>
<Title_id> Bu1032 </title_id>
<Title> The Busy Executive's DataBase Guide </Title>
<um_name> Marjorie Green </au_name>
<price> 19.99 </price>
<PUBDATE> 1991-06-12T07: 00: 00 </pubdate>
</Title>
Elastic
</documentelement>
</root>
In a typical web application, in order to obtain the maximum scalability and performance, it is likely to use web services or business objects to access data. In order to simplify these examples and focus on using DataGrid instead of data access, we choose to load data at one time when the application starts, and in the ASP application state in Global.asax Show.
Trunk from Global.asax:
public void application_onstart () {) {)
filestream fs = null;
dataset ds = null;
try {
fs = new filestream (server.mappath (titlesdb.xml), filemode.open,
FileAccess.read);
ds = new dataset ();
// Load the data in the XML file to the dataset
ds.readxml (fs);
} Finally {
if (fs! = null) {
fs.close ();
fs = null;
}
}
// Cchestrate the data set at a high speed to the application state so that it can be used in a single page
application [titlesDataSet] = ds;
}
datagrid1
DataGrid1 illustrates the basic usage of DataGrid, which explains how the control uses the least user code to generate a rich function.
FIG
Insert from DataGrid1.aspx:
<%@page Language = C# SRC = DataGrid.cs Inherits = SAMPLES.DATAGRIDPAGE%>
Elastic
<ASP: DataGrid Runat = Server ID = TitlesGrid>
</asp: datagrid>
The .aspx file above showed a statement without any attributes without any attributes of the DataGrid control.
datagrid.cs:
namespace Samples {
Elastic
Public Class DataGridpage: Page {
ProteCted DataGrid TitlesGrid;
Public iCollection GettitlesList () {
// Retore the title list from the DataSet of high -speed cache in the application state.
dataset titlesdataset = (dataset) Application [titlesDataSet];
if (TitlesDataSet! = NULL) {
Return titlesDataSet.tables [title] .defaultView;
}
else {
Return null;
}
}
Private void loadtitlesGrid () {) {)
// Search data from the database
iCollection Titleslist = GettitlesList ();
// Set the data source of the control
titlesGrid.datasource = Titleslist;
// And make it use this data source to build its project
titlesGrid.databind ();
}
ProteCted Override Void Overoad (EventArgs E) {{
base.onload (e);
if (! Ispostback) {
// See this page for the first time
loadtitlesGrid ();
}
}
}
}
The .cs file contains the code used for this page. This code is the same as the code function used in the DataList1 example. In the first request for this page, it covers the online method to retrieve data and set the DataSource property of the control before calling DataBind. This will make DataGrid create its project, which are necessary rows in the table. In the process of returning processing, DataGrid re -created the project from the status (this state includes the cell content saved in the last request).
This example illustrates the function of the AutogenerateColumns property of the DataGrid control. The default value of this attribute is true. When set to True, DataGrid will use Reflection to check its data source and objects and create a column for each public attribute or field. In this example, the control represents all the current fields in the "Title" table. This feature allows the list of the least user code to generate a list of any data source quickly and easily.
Each type of automatic column is Boundcolumn. This column type converts the attribute value associated with it into a string that needs to be used as a window.
datagrid2
DataGrid2 explains the DataGrid set by the Columns set in the .aspx file.
Figure 5. Examples generated by using the specified column DataGrid
Excerpt from DataGrid2.aspx:
<%@page Language = C# SRC = DataGrid.cs Inherits = SAMPLES.DATAGRIDPAGE%>
Elastic
<ASP: DataGrid Runat = Server ID = TitlesGrid
AutogenerateColumns = false>
<poperty name = columns>
<ASP: Boundcolumn HeadelText = Title DataField = Title/>
<ASP: Boundcolumn HeadelText = Author DataField = AU_NAME/>
<ASP: Boundcolumn Headertext = Date Published DataField = PUBDATE/>
<ASP: Boundcolumn HeadelText = Price DataField = Price/>
</Property>
</asp: datagrid>
This .ASPX file showed a DataGrid control with a column set by users. This example uses the same code -supported files as DataGrid1 because no code is required.
DataGrid's AutogenerateColumns property is set to fake, so as to prevent the control from automatically generate columns, and allows users to be responsible for defining columns that will be represented in the table.
There are many benefits:
You can control the order of columns. List in the order of a statement. On the other hand, the automatic column is represented by the order retrieved by the image. This order does not need to match the order order in the code or the sequence of the database table itself.
You can specify the header of each column with the column headerText property. In the previous example, the label header indicates the field name, which may not be appropriate. When using controls in this mode, Columbns also offers other setable attributes.
The type of automatic column is always Boundcolumn. Specify the column set so that the user can control the type of each column.
datagrid3
DataGrid3 is built on DataGrid2 by adding visual formatting and formatting.
Figure 6. Examples generated by the datagrid that sets the style and format attributes
Excerpt from DataGrid3.aspx:
<%@page Language = C# SRC = DataGrid.cs Inherits = SAMPLES.DATAGRIDPAGE%>
Elastic
<ASP: DataGrid Runat = Server ID = TitlesGrid
AutogenerateColumns = false
width = 80%
backcolor = white
borderWidth = 1px BorderStyle = solid cellpadding = 2 cellspacing = 0
borderColor = TAN
font-name = Song style FONT-siZe = 8pt>
<poperty name = columns>
<ASP: Boundcolumn HeadelText = Title DataField = Title/>
<ASP: Boundcolumn HeadelText = Author DataField = AU_NAME/>
<ASP: Boundcolumn Headertext = Date Published DataField = Pubdate
dataformatstring = {0: mmm yyyy}/>
<ASP: Boundcolumn HeadelText = Price DataField = Price
DataFormatstring = {0: C}>
<poperty name = itemStyle>
<ASP: TableItemstyle HorizontalaLign = Right/>
</Property>
</asp: Bounddcolumn>
</Property>
<poperty name = headstyle>
<ASP: TableItemstyle Backcolor = Darkred Forecolor = White
font-black = true/>
</Property>
<poperty name = itemStyle>
<ASP: TableItemstyle Forecolor = DARKSLATEBLUE/>
</Property>
<poperty name = AlternatingItemstyle>
<ASP: TableItemstyle Backcolor = Beige/>
</Property>
</asp: datagrid>
This .ASPX file showed the same DataGrid control statement as the previous, and set various style attributes. This will lead to a more attractive representation. There is still no need to make any changes to the code, and the use of code supported by the same examples as previous examples.
Because it is obtained from WebControl, the DataGrid control inherits style attributes such as Width, BackColor, BordersTyle, and Font.Name. In addition, DataGrid offers attributes such as Cellpadding, which are specific to the table. These attributes are allowed to customize controls on the whole.
The statement also displays several sets of project styles, such as Headers Style and AlternatingItemstyle. These styles control the appearance of their corresponding items. Please note that the style of the style appears in this example. The alternative projects are the same as the prospects of general projects, because their styles are combinations of AlternatingItemstyle and itemStyle. Finally, this example also explains the style of a specific column through the text in the right -to -alignment price column.
DataGrid also allows you to format the text content in its cell. This is completed by setting the DataFormatstring property value of Boundcolumn. The column uses its format to format the cell content of String.Format. This attribute can be preset or attached to any content with the formatting type (such as the date or currency). In addition, because the formatting considers the CultureInfo and requests of the current page, it also supports globalization. If there is no specified format, use the Tostring method of this value.
datagrid4
DataGrid4 explains how to use the selection in DataGrid by handling the SelectedIndindexchanged event.
Figure 7. Examples generated by allowing the DataGrid containing items
Test from DataGrid4.aspx:
<%@page Language = C# SRC = DataGrid4.cs Inherits = Samples.dataGrid4page%>
Elastic
<ASP: DataGrid Runat = Server ID = TitlesGrid
AutogenerateColumns = false
width = 80%
backcolor = white
borderWidth = 1px BorderStyle = solid cellpadding = 2 cellspacing = 0
borderColor = TAN
font-name = Song style FONT-siZe = 8pt
datakeyfield = title_id
onSeleCTEDEXCHANGED = onSelectExchangedEdEsgrid>
<poperty name = columns>
<ASP: ButtonColumn Text = Select Command = Select/>
<ASP: Boundcolumn HeadelText = Title DataField = Title/>
<ASP: Boundcolumn HeadelText = Author DataField = AU_NAME/>
<ASP: Boundcolumn Headertext = Date Published DataField = Pubdate
dataformatstring = {0: mmm yyyy}/>
<ASP: Boundcolumn HeadelText = Price DataField = Price
DataFormatstring = {0: C}>
<poperty name = itemStyle>
<ASP: TableItemstyle HorizontalaLign = Right/>
</Property>
</asp: Bounddcolumn>
</Property>
<poperty name = headstyle>
<ASP: TableItemstyle Backcolor = Darkred Forecolor = White
font-black = true/>
</Property>
<poperty name = itemStyle>
<ASP: TableItemstyle Forecolor = DARKSLATEBLUE/>
</Property>
<poperty name = AlternatingItemstyle>
<ASP: TableItemstyle Backcolor = Beige/>
</Property>
<poperty name = selectdItemstyle>
<ASP: TableItemstyle Backcolor = Palegoldenrod Font-Bold = True/>
</Property>
</asp: datagrid>
Elastic
<asp: label runat = server id = selectinfolabel font-name = Song style font-size = 8pt/>
In the .aspx file, a event processing program was registered for DataGrid's SelectedIndexchanged event event. This incident processing program is implemented in a code supported file. A ButtonColumn, which has been added to the column set as "select", makes DataGrid represent a additional column containing the Select button for each project. At the same time, SELECTEDITEMSTYLE is specified. This style is used to distinguish the projects from visually. Finally, DataGrid's DataKeyfield attribute is specified. This field will be placed in the DataGrid DataKeys collection, which will be used in files with code support.
datagrid4.cs:
namespace Samples {
Elastic
Public Class DataGrid4page: Page {
ProteCted DataGrid TitlesGrid;
Protected label searchinfolabel;
Public iCollection GettitlesList () {
// Retore the title list from the DataSet of high -speed cache in the application state.
dataset titlesdataset = (dataset) Application [titlesDataSet];
if (TitlesDataSet! = NULL) {
Return titlesDataSet.tables [title] .defaultView;
}
else {
Return null;
}
}
Private void loadtitlesGrid () {) {)
// Search data from the database
iCollection Titleslist = GettitlesList ();
// Set the data source of the control and reset its choice,
titlesGrid.datasource = Titleslist;
titlesGrid.SelectDindex = -1;
// And make the control use this data source to build its project
titlesGrid.databind ();
// Update selected title information
UpdateSelecttitalInfo ();
}
ProteCted Override Void Overoad (EventArgs E) {{
base.onload (e);
if (! Ispostback) {
// See this page for the first time
loadtitlesGrid ();
}
}
// Processing DataGrid's onselectindindindexchanged event
Protected void onSelectedInDindExchangedtitlesGrid (Object SENDER,
eventargs e) {
UpdateSelecttitalInfo ();
}
Private void updateSeSelecttitiveInfo () {{) {
// Get the selected index
int Selindex = TitlesGrid.SelectEx;
string selfieid = null;
string selectinfo;
if (selindex! = -1) {{
// Show the key field of selected title
SELTITLEID = (String) TitlesGrid.data [Selindex];
SelectionInfo = ID of selected title: + SELTITLEID;
}
else {
selectinfo = no title is currently selected.;
}
selectinfolabel.text = selectinfo;
}
}
}
This .cs file contains the logic of handling the SELECTEDINDEXCHANED event and the logic of the ID of the selected title at DataGrid. DataGrid handles the command event, which is triggered by buttons included in its project. It recognizes the standard command "Select", which makes it change its SelectedIndex property and triggers this incident to change the code of notifying the user.
In the process of implementing event processing programs, the example code calls the UpdateSelectTitleInfo method. This method is responsible for displaying information about the selected book title. In this example, the ID is the ID. In a more realistic scheme, this ID can be used to link a page to display more details about the selected title.
ID is retrieved by visiting the DataKeys collection. The collection is set in because of the DataKeyfield attribute. Usually, set it as the main keyword or other fields that can be identified by the household, and use this information as the guidelines in the follow -up database query or filter data.
This example shows how to further support operations such as selecting objects in the data source in addition to only objects in the data source. DataGrid contains support for several other features (such as sorting, paging, on -site editors, and TemplateColumns). However, these specific features exceed the scope of the discussion of this article and will be discussed in future articles.
Repeater, DataList or DataGrid?
Repeater, DataList and DataGrid control shared public programming models. At the same time, each control is designed to focus on a specific scheme. It is an important decision to choose the correct list of controls for the correct list. This section describes the function of the control hierarchy and the function of each control, as well as an example of the typical solution that each control may be used.
As you can see in the class structure below, Repeater is a small and light control. It only inherits the functions of the basic Control class, such as ID attributes and sub -control sets. On the other hand, the DataList control and DataGrid control inherit the WebControl function, such as style and appearance attributes.
Figure 8. List -binding control of the class level structure
In terms of object models, the Repeater control is the simplest control. It is also the smallest data binding control and basically different, that is, it does not force any special UI layout. The final indication method follows the method of generating text. The method is to repeat the template content specified for this control. This control does not provide any built -in support for styles and appearance attributes or behaviors. It is an excellent choice for a solution that needs to be fully controlled.
The DataList control is a repeater forced to use the column layout or stream layout. It inherits the appearance attributes implemented in WebControl and adds other style attributes that are suitable for items it created. The DataList control also includes support for its project standard operations (such as selecting, editing and deleting). It is very suitable for the sequence stream of the level or vertical projects distributed in a row or row.
The DataGrid control is forced to use the list or line layout. Similar to DataList, this control provides styles and appearance attributes. In addition to selecting and editing, DataGrid also supports advanced operations on the collection of the entire project, such as pages and sorting. One of the main differences between DataGrid and DataList is that DataGrid does not contain any template attributes, that is, the project or non -template of the DataGrid control. However, add TemplateColumn to the DataGrid to use the template in a specific column.
The following table is a summary of the function provided by the list binding control.
Function Repeater DataList DataGrid
The template is (required) or within (required) columns (optional)
Is the list layout?
Is the stream layout
Is the layout of the distribution/newspaper column style?
Whether the style and appearance attributes are
Select whether yes
Edit
Is it deleted?
No pagination
Is it sorted?
Related resources
With the QUICKSTART examples published by Microsoft .NET Framework SDK, there were several examples of these controls, and examples that explained the data accessing data with XML and Web services. The document attached to the SDK includes the conceptual data of the relevant topic, such as the ASP+ page framework and server control, and the reference bibliography of the object model as part of the control of this frame.