Introduced
We can change the GridView, DetailsView, and FormView styles by controlling HeaderStyle, RowStyle, AlternatingRowStyle, and other attributes, such as CssClass, Font, BorderWidth, BorderStyle, Bar, Width, height, etc.
In general, custom formatting is associated with the value of the data that we want to display. For example, in order to attract users ' attention to products that are empty, we can set the field UnitsInStock and UnitsOnOrder for the inventory to yellow for the 0 data background color. To highlight those expensive products, set the data font UnitsInStock higher than $75.00 to bold
GridView, DetailsView, FormView format customization can be done in a variety of ways, in this article we will use DataBound and rowdatabound two kinds of events to complete, in the next we will try to use the alternative way Using TemplateField in the GridView control
Use the DataBound event of the DetailsView control to bind the data to the DetailsView control, either by populating the data to the DataSource property from a data control or encoding, and calling its DataBind () method. The following events trigger
1.DataBinding Event Trigger
2. Data binding to data-bound controls
3.DataBound Event Trigger
Typically after 1,2,3 data will populate the data control with events immediately, we can also customize event handling to determine whether the data has been populated into the control and adjust the display format as we need it. We can do an example. We'll create a DetailsView to list the general information for a product, and when the UnitPrice is over $75.00 in bold, italic the font to display the UnitPrice value
Step 1: Display product information in DetailsView
Create a new customcolors.aspx page under the Customformatting folder, drag a DetailsView control from the toolbox to the page, The setting ID is bound to a new data source by Expensiveproductspriceinbolditalic and configures the GetProducts () method of this data source into the business object PRODUCTSBLL class. The detailed implementation of this step has been introduced in detail before, and here it ignores
When you bind ObjectDataSource to DetailsView, we can modify the field list, and I choose to remove ProductID, SupplierID, CategoryID, UnitsInStock, UnitsOnOrder , ReorderLevel and those fields that are not bound, they will not be shown in the DetailsView list, and those who have left can rename them and modify their display format. I also emptied the height and width properties of DetailsView so that when only one piece of data was displayed, there was no style confusion. Of course, we have to face the data is not only one so few, show how to do? We can check DetailsView IntelliSense to check that the Enable paging checkbox is checked, so that we can page through all the data.
Figure 1: Checking to see if the Enable Paging property is checked in the DetailsView value perception
After these changes, the DetailsView code is changed to
<asp:detailsview id= "DetailsView1" runat= "Server" allowpaging= "True" autogeneraterows= "False" datakeynames= " ProductID "datasourceid=" ObjectDataSource1 enableviewstate= "False" >
<Fields>
<asp: BoundField datafield= "ProductName" headertext= "Product" sortexpression= "ProductName"/> <asp
: BoundField datafield= "CategoryName" headertext= "Category" readonly= "True"
sortexpression= "CategoryName"/>
<asp:boundfield datafield= "SupplierName" headertext= "Supplier" readonly= "True"
sortexpression= "SupplierName"/>
<asp:boundfield datafield=
"QuantityPerUnit" HeaderText= "Qty/Unit" sortexpression= "QuantityPerUnit"/>
<asp:boundfield datafield= "UnitPrice" dataformatstring= "{0:c}" headertext= "Price"
htmlencode= "False" sortexpression= "UnitPrice"/>
</Fields>
</asp:d Etailsview>
You can then press F5 to perform a look
Figure 2:detailsview Control displays one data at a time
Step 2: Encode the values that determine the data in the DataBound event
In order to display those UnitPrice above $75.00 in bold, italic fonts, we first need to encode the UnitPrice value, and for DetailsView we can do it through the DataBound event. We select DetailsView and view the Properties view (F4-bit shortcuts), and if not, select the View Property window, Double-click the DataBound event or enter the event name you want to create, when you are sure you have selected DetailsView
Figure 3: Create an event handler for the DataBound event
The following code will be generated automatically in the code
protected void Expensiveproductspriceinbolditalic_databound (object sender, EventArgs e)
{
}
We can set the DetailsView binding (some strongly typed data rows (DataRow) as a strongly typed data table (DataTable) by the DataItem property, and when the datasheet (DataTable) is bound to DetailsView, The first row of the datasheet is automatically bound to the DetailsView DataItem property, and the DataItem property contains DataRowView (object type), and we can access a DataRowView by Productsrow DataRow instance, you can also detect the value of object to determine whether the Productsrow instance exists
The following code describes how to determine whether UnitPrice is bound to DetailsView and is higher than $75.00
protected void Expensiveproductspriceinbolditalic_databound (object sender, EventArgs e)
{
//Get the Productsrow object from the DataItem property ...
Northwind.productsrow Product = (Northwind.productsrow) (System.Data.DataRowView)
Expensiveproductspriceinbolditalic.dataitem). Row;
if (!product. Isunitpricenull () && product. UnitPrice > 75m)
{
//Todo:make the UnitPrice text bold and Italic
}
}
Note: When UnitPrice is null in the value of the database, it is important that we check to determine whether he is empty before binding to the Productsrow ' s UnitPrice property, because we can check this property to throw a strongly typed exception Strongtypingexception exception.
Step 3: Format UnitPrice in DetailsView
By this time we already know whether the UnitPrice is going to be bound higher than $75.00, now let's see how to adjust the UnitPrice format by encoding, we can modify detailsviewid.rows[index by modifying the line of data, And we can access Detailsviewid.rows[index]. Cells[index] To access a cell so that we can format this cell by modifying the formatting-related properties
Access to a row needs to get the index of a row, the index starting from 0, UnitPrice in DetailsView is line 15th, assuming he is in line fourth then we can access through EXPENSIVEPRODUCTSPRICEINBOLDITALIC.ROWS[4] . At this point, we can use the following code to show this line as bold, italic font
EXPENSIVEPRODUCTSPRICEINBOLDITALIC.ROWS[4]. Font.Bold = true;
EXPENSIVEPRODUCTSPRICEINBOLDITALIC.ROWS[4]. Font.Italic = true;
However, this will format the label and the value, and if we only want to format the value and we need to apply the formatting to the second grid of the current row, look at the following code
EXPENSIVEPRODUCTSPRICEINBOLDITALIC.ROWS[4]. CELLS[1]. Font.Bold = true;
EXPENSIVEPRODUCTSPRICEINBOLDITALIC.ROWS[4]. CELLS[1]. Font.Italic = true;
We can also use stylesheet to display tags and style-related information, rather than using a certain column of a certain row to format, we used CSS to control the format, open the Styles.css file, Add a new class named Expensivepriceemphasis follow the code below CSS
. Expensivepriceemphasis
{
font-weight:bold;
Font-style:italic;
}
Then databound the event, the CssClass of the set cell is Expensivepriceemphasis, added in databound event processing
When viewing chai (cost less than $75.00), the price will be shown in normal format Figure 4, but when viewing Mishi Kobe Niku, (the price is $97.00) will be displayed in our format (Figure 5)
Figure 4: Price below $75.00 will be displayed in normal format
Figure 5: The price is higher than the $75.00 will be bold, italic font display
The steps to bind to the FormView data using the DataBound event of the FormView control are similar to the steps DetailsView to create a DataBound event handler that declares a DataItem type property bound to the control and then performs the binding. However, they are updated in different ways
FormView does not include any bound columns and does not contain a collection of rows, but instead he consists of a series of template combinations containing a number of static HTML, Web controls, and binding expressions. Adjusting the appearance of FormView involves adjusting one or more FormView templates
Let's use FormView to list product items like the previous example, but this time we only display the name and units of a product with a units less than 10 in red font.
Step 1: Display product information in FormView
Add a FormView to customcolors.aspx, set its ID to lowstockedproductsinred, bind the data like the previous step to the ObjectDataSource, This will create ItemTemplate, EditItemTemplate, and InsertItemTemplate in FormView.
Remove EditItemTemplate and InsertItemTemplate and include only ProductName and UnitsInStock entries in ItemTemplate, and check for IntelliSense for allow Whether the paging (paging) tag is selected
After these operations FormView's code would probably be like this
<asp:formview id= "lowstockedproductsinred" runat= "datakeynames=" ProductID "datasourceid="
ObjectDataSource1 "allowpaging=" True "enableviewstate=" False ">
<ItemTemplate>
<b>product: </b>
<asp:label id= "Productnamelabel" runat= "server" text= ' <%# Bind ("ProductName")%> ' >
</asp:label><br/>
<b>units in stock:</b>
<asp:label id= "UnitsInStockLabel" runat= "Server" text= ' <%# Bind ("UnitsInStock")%> ' >
</asp:Label>
</ItemTemplate>
</asp:FormView>
Note The code that ItemTemplate contains:
• Static html– "Product:" and "Units in-Stock:" contains <br/> and <b> elements.
· Web Control – Two label controls, Productnamelabel and Unitsinstocklabel.
• Binding Expression –<%# bind ("ProductName")%> and <%# bind ("UnitsInStock")%> expression, bound value to label's Text property
Step 2: Encode the values that determine the data in DataBound event processing
When the FormView tag is complete, the next step is to determine whether the UnitsInStock value is less than or equal to 10, and here, like in DetailView, create the DataBound event first
Figure 6: Creating DataBound Event handling
In the event, declare the FormView DataItem property to the Productsrow instance, determine the Unitsinprice value and display the corresponding value in red font
protected void Lowstockedproductsinred_databound (object sender, EventArgs e)
{
//Get the Productsrow object From the DataItem property ...
Northwind.productsrow Product = (Northwind.productsrow) (System.Data.DataRowView)
Lowstockedproductsinred.dataitem). Row;
if (!product. Isunitsinstocknull () && product. UnitsInStock <=)
{
//Todo:make The Unitsinstocklabel ' s text red
}
}
Step 3: Format Unitsinstocklabel Label in FormView's ItemTemplate
The final step is to set the Unitsinstocklabel style to a red font in ItemTemplate, and find the control in Itemtempelete to use the FindControl ("ControlID") method
Webcontroltype somename = (webcontroltype) formviewid.findcontrol ("ControlID");
For our example, we can use the following code to find the label control
Label UnitsInStock = (label) Lowstockedproductsinred.findcontrol ("Unitsinstocklabel");
When we find this control, we can modify its corresponding style property, there is already a written lowunitsinstockemphasis CSS class in style.css, we use the following code to set the CSS class to the corresponding property
protected void Lowstockedproductsinred_databound (object sender, EventArgs e)
{
//Get the Productsrow object From the DataItem property ...
Northwind.productsrow Product = (Northwind.productsrow) (System.Data.DataRowView)
Lowstockedproductsinred.dataitem). Row;
if (!product. Isunitsinstocknull () && product. UnitsInStock <=
{
label UnitsInStock = (label) Lowstockedproductsinred.findcontrol ("Unitsinstocklabel ");
if (UnitsInStock!= null)
{
unitsinstock.cssclass = ' lowunitsinstockemphasis ';
}
}
}
Note: This approach can also be done in the FormView and GridView by setting the Templatefields to achieve the same effect. We will discuss templatefields in the next article. Figure 7 shows FormView when UnitsInStock is greater than 10, figure 8 shows a situation that is less than or equal to 10
Figure 7: In the case of higher than 10, no value is formatted
Figure 8: Less than or equal to 10 o'clock, values are displayed in red font
Customizing formatting with the RowDataBound event of the GridView
Before we discussed the steps to implement data binding in FormView and DetailsView, let's review
DataBinding Event Trigger
Data binding to data-bound controls
DataBound Event Trigger
Valid for FormView and DetailsView because only one data needs to be displayed, and in the GridView, all data is displayed, and step two is somewhat different than the previous three steps
In step two, the GridView lists all of the data, a GridViewRow instance is created and bound for one record, and two events per GridViewRow added to the GridView are triggered:
· rowcreated– triggered when GridViewRow is created
· rowdatabound– is triggered when the current record is bound to GridViewRow.
For the GridView, use the following procedure
DataBinding Event Trigger
Data binding to data-bound controls
For each row of data ...
A. Creating GridViewRow
B. Triggering rowcreated events
C. Binding data to GridViewRow
D. Triggering RowDataBound events
E. Add GridViewRow to Rows collection
DataBound Event Trigger
To customize the format GridView separate record, we need to create event handling for the RowDataBound event, let's add a GridView to customcolors.aspx and display name, category, and Price, Highlight products with a yellow background that are less than $10.00
Step 1: Display product information in the GridView
Add a GridView to the bottom of the FormView, Set ID to highlightcheapproducts. We have previously set up a ObjectDataSource to get product data, and now we bind the GridView to ObjectDataSource. The binding column of the edit GridView contains the Name.categorie,price property of the product. When you're done, the code for the GridView will be:
<asp:gridview id= "highlightcheapproducts" runat= "Server" autogeneratecolumns= "False"
datakeynames= " ProductID "datasourceid=" ObjectDataSource1 enableviewstate= "False" >
<Columns>
<asp: BoundField datafield= "ProductName" headertext= "Product" sortexpression= "ProductName"/> <asp
: BoundField datafield= "CategoryName" headertext= "Category" readonly= "True"
sortexpression= "CategoryName"/>
<asp:boundfield datafield= "UnitPrice" dataformatstring= "{0:c}" headertext= "Price"
Htmlencode= "False" sortexpression= "UnitPrice"/>
</Columns>
</asp:GridView>
Figure Nine shows the results of the browser view
Figure 9:gridview Displays the name of the product, category, price
Step 2: Encode the values that determine the data in RowDataBound event handling
When Productsdatatable is bound to Gridview,gridview, several productsrow are generated. The DataItem property of the GridViewRow will generate an actual productrow. After the RowDataBound event of the GridView, in order to determine the value of UnitsInStock, we need to create RowDataBound event handling. In which we can determine the value of UnitsInStock and do the corresponding formatting eventhandler the same as the previous two
Figure 10: Event handling for the RowDataBound event that created the GridView
The following code will be generated automatically in the background code
protected void Highlightcheapproducts_rowdatabound (object sender, GridViewRowEventArgs e)
{
}
When the RowDataBound event is triggered, the second parameter GridViewRowEventArgs contains a reference to GridViewRow, and we use the following code to access the Productsrow in GridViewRow
protected void Highlightcheapproducts_rowdatabound (object sender, GridViewRowEventArgs e)
{//Get the Productsrow Object from the DataItem property ...
Northwind.productsrow Product = (Northwind.productsrow) ((System.Data.DataRowView)
E.row.dataitem). Row;
if (!product. Isunitpricenull () && product. UnitPrice < 10m)
{
//todo:highlight the row yellow ...
}
}
When using RowDataBound event processing, the GridView consists of different types of rows, and the event occurs for all row types, and the GridViewRow type can be determined by the RowType property, which can be one of the following types
· A record in the DataSource of Datarow–gridview
· Emptydatarow–gridview's datasource shows an act of empty
· footer– the bottom row; display the Showfooter property of the GridView
· header– Head Line; Display by the Showheader property of the GridView
· Pager–gridview, a line that shows the markup for pagination
· separator– is not available for the GridView, but it is useful for the RowType properties of DataList and Reapter, and we will discuss them in future articles
When the above four species (DataRow, Pager Rows Footer, Header) do not fit the corresponding value, an empty data item is returned, so we need to check the RowType property of the GridViewRow in the code to determine:
protected void Highlightcheapproducts_rowdatabound (object sender, GridViewRowEventArgs e)
{
//Make sure we are Working with a DataRow
if (e.row.rowtype = = Datacontrolrowtype.datarow)
{
//Get the Productsrow object from T He DataItem
... Northwind.productsrow Product = (Northwind.productsrow) ((System.Data.DataRowView)
E.row.dataitem). Row;
if (!product. Isunitpricenull () && product. UnitPrice < 10m)
{
//todo:highlight row yellow ...
}
}}
Step 3: Highlight those lines with yellow UnitPrice less than $10.00
We need to visit Gridviewid.rows[index] to access the line of index corresponding, Gridviewid.rows[index]. Cells[index] to access a cell. However, when the RowDataBound event is triggered, GridViewRow is not added to the Rows collection, so we cannot pass the current GridViewRow instance in RowDataBound event processing
Instead, we can go through E. Row to access. To highlight a line, we use the following code
E.row.backcolor = System.Drawing.Color.Yellow;
We can also get the same effect through CssClass (recommended)
protected void Highlightcheapproducts_rowdatabound (object sender, GridViewRowEventArgs e)
{
//Make sure we are Working with a DataRow
if (e.row.rowtype = = Datacontrolrowtype.datarow)
{
//Get the Productsrow object from T He DataItem
... Northwind.productsrow Product = (Northwind.productsrow) ((System.Data.DataRowView)
E.row.dataitem). Row;
if (!product. Isunitpricenull () && product. UnitPrice < 10m)
{
E.row.cssclass = "affordablepriceemphasis";
}
}}
Figure 11: The required rows are highlighted in yellow
Summarize
In this article we demonstrate a method for customizing the format GridView, DetailsView, and FormView based on data binding. To do this, we create databound or RowDataBound events, and in order to access the DetailsView or FormView data binding, we can pass the DataItem attribute. For the GridView, the DataItem property of each GridViewRow instance contains the bound data (available in RowDataBound event processing)
In order to adjust the format, we may need to access a particular row, in the GridView and DetailsView we can access through the index, while in the FormView we need to use FindControl ("ControlID"), while FindControl ("ControlID") usually has access to a control in the Web control Tempelete. In the next installment, we'll discuss how to use Tempeletes in the GridView and DetailsView, and also discuss some other custom formatting methods
I wish you a happy programming!
Introduction of the author
Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog http://scottonwriting.net/.