Grid implementation of ASP. NET Server control development (iv) postback events

Source: Internet
Author: User

Link jumps are used when using the grid. If it's just a normal link jump, it can be implemented using the A-tag href. But sometimes, we want to be able to trigger a postback event when the link jumps, make some processing in the background, and then jump. How can this be done? We can define a linkbuttonfield to implement. 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{///<summary>//    Table link button columns //    </summary>    [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 appropriate type in the column editor, with the following code:

    [Designer ("AspNetServerControl.Design.GridDesigner,")] [ToolBoxData ("<{0}:grid title=\" grid\ "runat=\" Server\ "><Columns></Columns></{0}:Grid>") ] [ToolboxBitmap (typeof (Grid), Toolbox. Grid.bmp ")] [Description (" Table control ")] [ParseChildren (true)] [PersistChildren (false)] [ControlBuilder (typeof (Notall Owwhitespaceliteralsbuilder)] [System.Security.Permissions.PermissionSet ( System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] public class grid:controlbase, ipostbackevent Handler {//////attribute code refer to the grid implementation developed by the ASP. HTML markup Rendering #region event #region Onrowcommand////defines the Cl        Ick event.        public event eventhandler<gridcommandeventargs> 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 (); <summary>///In-line events///</summary> [Category (Categoryname.action)] [Description        ("In-line event")] Public event eventhandler<gridcommandeventargs> Rowcommand {add {Event            S.addhandler (_rowcommandhandlerkey, value);            } remove {Events.removehandler (_rowcommandhandlerkey, value); }}///<summary>//Trigger in-line events///</summary>//<param name= "E" > Event parameters & lt;/param> protected virtual void Onrowcommand (Gridcommandeventargs e) {EVENTHANDLER&LT;GRIDC            Ommandeventargs> handler = Events[_rowcommandhandlerkey] as eventhandler<gridcommandeventargs>;            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 ("<table id=\" {0}\ "name=\" {1}\ "rules=\" all\ "border=\" 1\ "cellspacing=\" 0\ "style=            \ "Width:100%;border-collapse:collapse;\" > ", UniqueID, UniqueID));            Renderheader (writer);            Renderbody (writer); Writer.        Write ("</table>");            } private void Renderbody (HtmlTextWriter writer) {DataTable dt = DataSource as DataTable; if (dt = = NULL | | dt.            Rows.Count <= 0) {return; } writer.            Write ("<tbody>");            int rowIndex = 0;            int columnindex = 0; foreach (DataRow row in dt. Rows) {writer.                Write (String.Format ("<tr {0}>", Getrowstyle ())); ColuMnindex = 0;                    foreach (gridcolumn column in Columns) {if (column is Linkbuttonfield) {writer.                                                    Write (String.Format ("<td {0}><a {1} name=\" {2}\ ">{3}</a></td>",  Getitemstyle (column), Getlinkbuttonpostback (column as Linkbuttonfield, RowIndex, columnindex), column. UniqueID, Row[column.                    DataField])); } else {writer. Write (String.Format ("<td {0}>{1}</td>", Getitemstyle (column), Row[column.                    DataField]));                } columnindex++; } writer.                Write ("</tr>");            rowindex++; } writer. Write ("</tboDy> ");            } 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, Linkbutt On.            CommandArgument);            String ClientScript = Page.ClientScript.GetPostBackClientHyperlink (this, ARG);            String href = String.Format ("href=\" {0}\ "", ClientScript);        return href;            }///other code refer to the grid implementation developed by the ASP (b) HTML markup 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); }            }        }


The 1.IPostBackEventHandler interface needs to implement the RaisePostBackEvent method.

2. When a page postback occurs, it is indexed to the corresponding event by the control's name and then back to the target. So for a grid control, we have to assign the name to a value at render, and then match it when the postback script is generated.

(1) So the name of the table tag in the render function is assigned a value, where UniqueID is used to ensure uniqueness.

(2) At the same time in Renderbody, if it is a linkbuttonfield column, add a postback script. When a linkbuttonfield is rendered to a cell in a table, the a tag is used to render, and its href is assigned a corresponding script. Generate the appropriate postback script in Getlinkbuttonpostback.

(3) In the Getlinkbuttonpostback function, the column and row indexes of the cell, together with the CommandName and commandargument of the Linkbuttonfield, are used as postback parameters. At the same time, for the sake of distinction, command is used as a prefix and as a delimiter between parameters. Using Page.ClientScript.GetPostBackClientHyperlink to generate a postback of the JS script, using the system method is simple, of course, you can write the script directly, the code is as follows.

Javascript:__dopostback (' Grid_edit ', ' Command$0$3$link$cmdarg '

3. After receiving the RaisePostBackEvent event, the corresponding parameters are separated and processed accordingly. In order to participate in the event that is called after using the grid to customize the postback, we have customized a Onrowcommand event.

The 4.OnRowCommand event is made up of three parts.

(1) Unique key: Use static read-only object, which is _rowcommandhandlerkey.

(2) Add the event to the processing list of the delegate event, which is Rowcommand. There is also a direct use of the delegate to define, but the performance is less than this definition. The direct definition of a delegate is, in principle, thread-safe. In order to be able to better customize the event, we define an event parameter Gridcommandeventargs. The code is shown later in this article.

(3) The Onrowcommand event implemented by the developer of the grid is equivalent to the button's onclick event. Note that the name of this event must correspond to the previous delegate, which adds only one on to the front.


Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace aspnetservercontrol{//<summary>///Table row command event arguments///</summary> public class Gridcommand        Eventargs:eventargs {private int _rowindex;  <summary>////Line index///</summary> public int RowIndex {get {return _rowindex;        } set {_rowindex = value;}        } private int _columnindex; <summary>////Column index///</summary> public int ColumnIndex {get {ret Urn _columnindex;        } set {_columnindex = value;}        } private string _commandname;  <summary>///Command name///</summary> public string CommandName {get { return _commandname;        } set {_commandname = value;}        } private string _commandargument; ///<summary>///Command parameter///</summary> public string CommandArgument {get            {return _commandargument;}        set {_commandargument = value;} }///<summary>//constructor///</summary>//<param name= "RowIndex" > Row index </p aram>//<param name= "columnindex" > Column index </param>//<param name= "commandName" > Command name </ param>//<param name= "commandargument" > Command Parameters </param> public Gridcommandeventargs (int rowinde            x, int columnindex, string commandName, String commandargument) {_rowindex = RowIndex;            _columnindex = ColumnIndex;            _commandname = CommandName;        _commandargument = CommandArgument; }    }}

After you have done this, you can use it.

The UI code is as follows:

 <div> <s:grid runat= "Server" id= "Grid_edit" onrowcommand= "Grid_edit_rowcommand" > &L T RowStyle height= "50px;"/> <Columns> <s:boundfield runat= "Server" id= "boundf                    Ield1 "headertext=" article number "datafield=" no "> <itemstyle horizontalalign=" Center "/> </S:BoundField> <s:boundfield runat= "Server" id= "BoundField2" headertext= "type" DataField                    = "Type" > <itemstyle horizontalalign= "Center"/> </S:BoundField>                        <s:boundfield runat= "Server" id= "BoundField3" headertext= "state" datafield= "status" > <itemstyle horizontalalign= "Center"/> </S:BoundField> <s:link                        ButtonField runat= "Server" id= "LinkButtonField1" headertext= "link" datafield= "link" Commandname= "LINK "> </S:LinkButtonField> </Columns> </S:Grid> &lt ;/div>

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", ""}); Dt.            Rows.Add (new string[] {"H10002", "vegetables", "Pending Sale", ""}); Dt.            Rows.Add (new string[] {"H10003", "Fruit", "Pending Sale", ""}); Dt.            Rows.Add (new string[] {"H10004", "Appliance", "in Sales", ""});        return DT;            } protected void Grid_edit_rowcommand (object sender, Aspnetservercontrol.gridcommandeventargs e) { Code that needs to be processed} 
The postback event of the grid is implemented. The other postback processing, can imitate this.

Grid implementation of ASP. NET Server control development (iv) postback events

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: 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.