Grid implementation developed by Asp. Net Server controls (4) event sending back

Source: Internet
Author: User

Grid implementation developed by Asp. Net Server controls (4) event sending back

When using Grid, link jump is used. If it is just a normal link jump, you only need to use the href of the a tag. However, sometimes, we want to trigger a send-back event when the link is redirected, make some processing in the background, and then jump. How can this be achieved? We can define a LinkButtonField for implementation. The Code is as follows:

Using System; using System. collections. generic; using System. componentModel; using System. linq; using System. text; using System. threading. tasks; using System. web. UI; namespace AspNetServerControl {////// Table link button column ///[ToolboxItem (false)] [ParseChildren (true)] [PersistChildren (false)] public class LinkButtonField: BaseField {}}

Note: LinkButtonField is also inherited from BaseField. After adding a column field, we need to add the corresponding type in the column editor. The Code is as follows:

[Designer ("AspNetServerControl. design. gridDesigner, AspNetServerControl. design ")] [ToolboxData (" <{0}: Grid Title = \ "Grid \" runat = \ "server \">
 
 ")] [ToolboxBitmap (typeof (Grid)," toolbox.Grid.bmp ")] [Description (" Table Control ")] [ParseChildren (true)] [PersistChildren (false)] [ControlBuilder (typeof (NotAllowWhitespaceLiteralsBuilder)] [System. security. permissions. permissionSet (System. security. permissions. securityAction. demand, Name = "FullTrust")] public class Grid: ControlBase, IPostBackEventHandler {// For the attribute code, see Asp. net Server Control development Grid Implementation (2) Html Tag rendering # region event # region OnRowCommand // Defines the Click event. // public event EventHandler
 
  
RowCommand; // Invoke delegates registered with the Click event. // protected virtual void OnRowCommand (GridCommandEventArgs e) // {// if (RowCommand! = Null) // {// RowCommand (this, e); //} private static readonly object _ rowCommandHandlerKey = new object ();///
  /// In-row event ///[Category (CategoryName. ACTION)] [Description ("intra-row event")] public event EventHandler
  
   
RowCommand {add {Events. AddHandler (_ rowCommandHandlerKey, value);} remove {Events. RemoveHandler (_ rowCommandHandlerKey, value );}}///
   /// Trigger an in-row event //////
   Event ParametersProtected virtual void OnRowCommand (GridCommandEventArgs e) {EventHandler
   
    
Handler = Events [_ rowCommandHandlerKey] as EventHandler
    
     
; If (handler! = Null) {handler (this, e) ;}# endregion # endregion protected override void Render (HtmlTextWriter writer) {base. render (writer); if (_ columns = null) {return;} writer. write (String. format ("
     
 
  
      
", UniqueID, UniqueID); // RenderHeader (writer); RenderBody (writer); writer. Write ("
     
 
");} Private void RenderBody (HtmlTextWriter writer) {DataTable dt = DataSource as DataTable; if (dt = null | dt. rows. count <= 0) {return;} writer. write (""); Int rowIndex = 0; int columnIndex = 0; foreach (DataRow row in dt. Rows) {writer. Write (String. Format ("", GetRowStyle (); columnIndex = 0; foreach (GridColumn column in Columns) {if (column is LinkButtonField) {writer. Write (String. Format ("{3}", GetItemStyle (column), GetLinkButtonPostBack (column as LinkButtonField, rowIndex, columnIndex), column. uniqueID, row [column. dataField]);} else {writer. write (String. format ("{1}", GetItemStyle (column), row [column. DataField]);} columnIndex ++;} writer. Write (""); RowIndex ++;} writer. Write ("");} Private String GetLinkButtonPostBack (LinkButtonField linkButton, int rowIndex, int columnIndex) {if (linkButton = null) {return" ";} String arg = String. format ("Command ${0 }$ {1 }$ {2 }$ {3}", rowIndex, columnIndex, linkButton. commandName, linkButton. commandArgument); String clientScript = Page. clientScript. getPostBackClientHyperlink (this, arg); String href = String. format ("href = \" {0} \ "", clientScript); return href ;}// for other code, see Asp. net Server Control development Grid Implementation (2) Html Tag rendering public void RaisePostBackEvent (string eventArgument) {if (eventArgument. startsWith ("Command $") {string [] commandArgs = eventArgument. split ('$'); if (commandArgs. length = 5) {GridCommandEventArgs gridCommandEventArgs = new GridCommandEventArgs (Convert. toInt32 (commandArgs [1]), Convert. toInt32 (commandArgs [2]), commandArgs [3], commandArgs [4]); OnRowCommand (gridCommandEventArgs );}}}


Note:

1. The IPostBackEventHandler interface must implement the RaisePostBackEvent method.

2. During page sending back, the corresponding event is indexed by the Control name and then sent back to the target. Therefore, for the Grid control, we must assign a value to the name during Render, and then assign the value to it when generating the re-sending script.

(1) Therefore, the name of the table tag in the Render function must be assigned a value. Here, UniqueID is used to ensure uniqueness.

(2) At the same time, in the RenderBody, if it is a LinkButtonField column, it will add a resend script. When LinkButtonField is rendered to a table cell, it is rendered using the mark and Its href value is assigned to the corresponding script. Generate the corresponding send-back script in GetLinkButtonPostBack.

(3) In the GetLinkButtonPostBack function, the column index and row index of the cell, the CommandName and CommandArgument of LinkButtonField are used as the return parameters. To facilitate differentiation, use Command as the prefix and use $ as the separator between parameters. Use Page. ClientScript. GetPostBackClientHyperlink to generate the js script for sending back. The system method is simple. Of course, you can also directly write the script. The Code is as follows.

javascript:__doPostBack('Grid_Edit','Command$0$3$LINK$cmdarg'

3. After RaisePostBackEvent receives the send-back event, the corresponding parameters are separated and processed accordingly. To enable the use of Grid to customize the events called after the sending back, We have customized an OnRowCommand event.

4. The OnRowCommand event is composed of three parts.

(1) unique KEY: Use a static read-only object, that is, _ rowCommandHandlerKey.

(2) Add the event to the processing list of the delegate event, that is, RowCommand. There are also some definitions using delegation directly, but the performance is not as good as this definition. The principle of direct definition of delegation is thread security. To better customize events, we define an event parameter GridCommandEventArgs. For the code, see the following.

(3) The OnRowCommand event implemented by the Grid developer is equivalent to the OnClick event of the button. Note that the name of this event must correspond to the previous delegate, that is, only one On is added to the previous delegate.

GridCommandEventArgs

Using System; using System. Collections. Generic; using System. Linq; using System. Text; using System. Threading. Tasks; namespace AspNetServerControl {////// Table line command event parameters ///Public class GridCommandEventArgs: EventArgs {private int _ rowIndex ;////// Row index ///Public int RowIndex {get {return _ rowIndex;} set {_ rowIndex = value ;}} private int _ columnIndex ;////// Column index ///Public int ColumnIndex {get {return _ columnIndex;} set {_ columnIndex = value;} private string _ commandName ;////// Command name ///Public string CommandName {get {return _ commandName;} set {_ commandName = value ;}} private string _ commandArgument ;////// Command parameters ///Public string CommandArgument {get {return _ commandArgument;} set {_ commandArgument = value ;}}////// Constructor //////Row Index///Column Index///Command name///Command ParametersPublic GridCommandEventArgs (int rowIndex, int columnIndex, string commandName, string commandArgument) {_ rowIndex = rowIndex; _ columnIndex = columnIndex; _ commandName = commandName; _ commandArgument = commandArgument ;}}}

After completing these steps, you can use them.

The UI code is as follows:

             
                 
                  
                      
                           
                        
                       
                           
                        
                       
                           
                        
                       
                       
                   
              
         

The corresponding background code is as follows:

Private void InitLoad () {Grid_Edit.DataSource = GenerateData ();} private DataTable GenerateData () {DataTable dt = new DataTable (); dt. columns. add ("NO"); dt. columns. add ("Type"); dt. columns. add ("Status"); dt. columns. add ("Link"); dt. rows. add (new String [] {"H10001", "food", "sold out", "http://www.baidu.com"}); dt. rows. add (new String [] {"H10002", "Vegetables", "to be Sold", "http://www.baidu.com"}); dt. rows. add (new String [] {"H10003", "Fruit", "to be Sold", "http://www.baidu.com"}); dt. rows. add (new String [] {"H10004", "appliance", "sales", "http://www.baidu.com"}); return dt;} protected void Grid_Edit_RowCommand (object sender, AspNetServerControl. gridCommandEventArgs e) {// code to be processed}
In this way, the Grid sending event is implemented. You can copy this for other sending replies.




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.