Step6page.cs:
Namespace Samples {
...
Public class step6page: Page {
/ / Update the currently selected author and reload the title corresponding to the selected content
// grid
protected void loadingtitlesgrid () {
Updateselection ();
Titlesgrid.databind ();
}
// Treat the Cancelcommand event in the book name grid,
// End Edit without administration
Protected Void Oncancelcommandtitlesgrid (Object Sender,
DataGridCommandEventArgs e) {
Titlesgrid.editIndEx = -1;
LoadTitlesgrid ();
}
// Treply handle the editcommand event in the book name grid,
// Start editing a row
Protected Void OneDitCommandtitlesgrid (Object Sender,
DataGridCommandEventArgs e) {
Titlesgrid.edititeMindex = E.Item.ItemIndex;
LoadTitlesgrid ();
}
// Treated the UpdateCommand event in the book name grid to apply
// Changes made and end editing
Protected void onupdateCommandtitlesgrid (Object Sender,
DataGridCommandEventArgs e) {
TextBox preformExt =
(TextBox) E.Item.FindControl ("Column3Control");
String newprice = prictext.text.substring (1);
DataSet DS = GetSessionData ();
DataTable TitleStable = ds.tables ["Title"];
String TitleID =
(String) Titlesgrid.DataKeys [E.Item.ItemIndex];
DataRow [] rows = TitleStable.select ("Title_ID = '"
TitleID "'");
DataRow Editrow = ROWS [0];
Editrow.beginedit ();
Editrow ["price"] = newprice;
Editrow.endedit ();
Editrow.acceptchanges ();
Titlesgrid.editIndEx = -1;
LoadTitlesgrid ();
}
}
}
The EditCommand event is triggered when you click the Edit button. Simply set the DataGrid's EditIndex property to the properties of the index containing the clicked button. To prevent editing a certain one, return it without any action. Alternatively, you must continue editing, you must reload the data source and call DATABIND. This is done by calling the loadtitlesgrid method.
The second event you must handle is the CancelCommand event. This is caused by clicking the CANCEL button. Implementation is very similar to the previous processor. To end the editing, just reset the EditItemIndex property to? And reload the data source. If you need to maintain the editing mode of the row, you only need to return any actions.
The last event to be processed is the UpdateCommand event, which is raised when you click the Update button. Here is where practical work. Add a new value from the controls existing in the project, then update the data source. Once the new value is used, the EditItemIndex is reset to be to returned to read-only mode and reload the control along with its data source. For the first two events, you can return from this function without any action to maintain the editing mode status of the line. This step is again an exemplified data binding model implemented in the control. In this implementation, the data source is only required to change from read-only mode to edit mode or at a certain state. Note that DataGrid itself does not update its data source. In essence, data binding is one-way. The purpose of this model is to let you have control of the data source update. In most typical applications, the update requires pretreatment and is called by a business object or a stored process. In addition, one-way data binding does not require a real-time data source every time.
Step 7: Using Templates
The DataGrid control supports the in-line template by using TemplateColumns. The contents of the cells associated with these columns can be fully disciplined. This step uses TemplateColumn to enhance the editor supported in the previous step.
Figure 8. Complete the page behind step 7
Titles DataGrid From:
Step7.aspx:
...> ... Text = '<% # DataBinder.eval (Container.DataItem, "Price", "{0: C}")%> '/> template> ControlTovAlidate = "deflerxt" Display = "Dynamic">
Align = "absmiddle"> asp: requiredfieldValidator> ControlTovAlidate = "deflerxt" Display = "Dynamic" ValidationExpression = "/ $ [0-9] (/. [0-9] [0-9]?)?">>
Title = "invalid currency value" align = "absmiddle"> asp: regularExpressionValidator> Text = '<% # DataBinder.eval (Container.DataItem, "Price", "{0: C}")%> ' Width = "45px" BorderStyle = "Solid" borderwidth = "1px" Bordercolor = "Black"> asp: textbox> template> Property> Property> asp: templateColumn> Property> ... ask: DataGrid> Controls Declaration Shows TemplateColumn Add to Column Sets to replace the BoundColumn in the price field. TemplateColumns is another extension mechanism for DataGrid. It can be fully customized to the UI in the table format layout created by the DataGrid. TemplateColumn also provides template properties such as ItemTemplate and EditItemplate, so you can specify controls that should be used in cells associated with columns. In this example, ItemTemplate contains a Label control, which is bound to the price field. This is essentially imitating the function of BoundColumn. Interestingly, the EditItemTemplate template is used in the cell in edit mode. The sample puts a Textbox into the template that has been bound to the price field. This provides the same function as BoundColumn. The template contains a wide variety of enhancements. First, the template allows for greater control to TextBox, so you can create more attractive editing UIs. Second, allow you to place the verification control, so that you can verify it. In this sample, RequiredFieldValidator ensures that TextBox always contains a value, while RegulaRexpressionValidator ensures that the text contains a valid currency value. The most exciting aspect of this feature is to automatically verify client-end verification. The ASP Verification Control automatically verifies client-side authentication and enables error indicators on a feature-rich browser client, so that there is no need to go to and from the process and fall to the sub-client authentication. STEP7PAGE.CS: Namespace Samples { ... Public Class Step7page: Page { // Treated the UpdateCommand event in the book name grid to apply // Changes made and end editing (when the page is active) Protected void onupdateCommandtitlesgrid (Object Sender, DataGridCommandEventArgs E) { IF (isvalid) { TextBox preformExt = (TextBox) E.Item.FindControl ("Prictext"); String newprice = prictext.text.substring (1); DataSet DS = GetSessionData (); DataTable TitleStable = ds.tables ["Title"]; String TitleID = (String) Titlesgrid.DataKeys [E.Item.ItemIndex]; DataRow [] rows = TitleStable.select ("Title_ID = '" TitleID "'"); DataRow Editrow = ROWS [0]; Editrow.beginedit (); Editrow ["price"] = newprice; Editrow.endedit (); Editrow.acceptchanges (); Titlesgrid.editIndEx = -1; LoadTitlesgrid (); } } } } The unique change of the support code is related to the validity of the page before updating the data source. Verify controls automatically update the IsValid property of the page. Check the effectiveness is done in the UpdateCommand event processor. As mentioned in step 6, the editing mode of the line will remain from the event processor without taking any action. Therefore, all update logic will be performed when and only when the page is in an active state. Confirm that the control will automatically display its error messages when it is invalid, and no supplemental code is required. Step 8: Customized columns As you can see, the DataGrid control supports standard columns, such as BoundColumn, ButtonColumn, and TemplateColumn. This control also allows you to extend control with your column type. These new columns provide a high degree of flexibility. This step implements a custom column named ImageColumn, which is used to display an image for each row with image URL data binding. Figure 9. Complete the page Titles DataGrid and ImageColumn from step 8 From: step8.aspx: step8.aspx: <% @ register tagprefix = "s" namespace = "samples"%> ... ...> Imageformatstring = "images / title- {0} .gif" /> Property> ... ask: DataGrid> This page contains a register instruction for mapping the Public class imagecolumn: column { Private propertyDescriptor imagefielddsc; Public imagecolumn () { } Public string imagefield { Get { Object o = state ["imagefield"]; RETURN (O! = null)? (String) o: string.empty; } SET { State ["Imagefield"] = Value; } } Public string imageformatstring { Get { Object o = state ["imageformatstring"]; RETURN (O! = null)? (String) o: string.empty; } SET { State ["ImageformatString"] = Value; } } / / Create in the cell associated with this column // control Public Override Void Initializecell (Tablecell Cell, Int columnIndex, ListitemType itemtype) { Base.initializecell (Cell, ColumnIndex, ItemType); IF (itemType == ListItemType.Item) || (itemtype == ListiteMTYPE.AlternatingItem) || (itemtype == ListiteMTYPE.SELECTEDITEM) || (ItemType == ListItemType.editItem)) { Image image = new image (); Image.id = column.getColumnControlid (ColumnIndex, -1); Cell.Controls.Add (Image); IF (imagefield.length! = 0) { Image.addondataBind (New EventHandler (this.ondataBindColumn); } } } // Load the data into the control created in Initializecell Private Void OnDataBindColumn (Object Sender, Eventargs E) { Image BoundImage = (image) sender; DataGridItem Item = (DataGridItem) boundimage.namingcontainer; Object DataItem = item.dataItem; IF (isfirstdataBind ()) { String imagefield = imagefield; ImageFieldDesc = TypedScriptor.getProperties [imagefield]; if (imagefielddesc == null) { Throw New Exception ("Invalid Property: '" ImageField "'"); } OnfirstDataBindHandLED (); } Object data = imagefieldDesc.getValue (DataItem); IF (Data! = NULL) { String Format = imageformatstring; IF (Format.length! = 0) { Boundimage.ImageURL = String.Format (Format, DATA); } Else { Boundimage.imageURL = data.toString (); } } } } } Each column used by the DataGrid control is derived from an abstract column class. Column Types implement a variety of properties (such as headerText), and all the forms commonred in all column types. ImageColumn class is used to add properties for its specific features, such as ImageField and ImageFormatString properties. These properties are implemented by depositing each value in the list of states. The state of the column is automatically received during the round-trip process of the DataGrid control. The most important virtual method of each column is the initializecell method. DataGrid urges each column to initialize the cell associated with the column. When implementing the method, column creation the control it needs and add them as a sub-cell of the cell. The created control may vary from the ItemType parameter, which indicates the itemType property containing the column of the cell. The Column class itself contains logic for generating headers and tails. ImageColumn just creates an Image control when performing self-implementation. It also adds an event processor to Image's DataBind property. Once the column is created, DataGrid is binded to it. In this process, the columns are allowed to customize the controls created in Initializecell by means of data associated with columns. ImageColumn retrieves the value of the field it binds, generates a URL using the format specified by the user, then uses the result string to set the image of the image. Conclusion The DataGrid control simplifies a number of common web applications, including read-only reports to interactive application UI. This control is superior to traditional ASP programming. It converts the logical encapsulation of the converted object model and the data binding to the browser-independent HTML expression function. The retransmission data is also processed, and the details of the translation of the client event will be processed into the server event. The control is designed to express your data without having to make too many development efforts. As the application requirements change, and you start using DataGrid's various features, you can gradually add other features. This control is now available in Microsoft® .NET SDK and Framework. The SDK also includes supplemental documents and multiple samples that can be used to start; both implement the materials provided herein.