Requirements
The gridview/DataGrid itself supports row selection events (by setting button/linkbutton. commandname = "selected" and processing it in the selectedindexchanged event ).
However, sometimes we want users to trigger an event by clicking any position in a row of the gridview/DataGrid and handle the event on the server. Now we can implement this function.
Implementation Method
Here we take a bit of "hack ":
The client-side Javascript is used to trigger click events for hidden buttons (both button and linkbutton are supported) in the row.
Main Code
<Asp: gridview id = "gridview1" runat = "server" autogeneratecolumns = "false" onrowcommand = "gridview1_rowcommand" onrowdatabound = "gridview1_rowdatabound">
<Columns>
<Asp: templatefield headertext = "productname">
<Itemtemplate>
<% # Eval ("productname") %>
<Asp: button id = "btnhiddenpostbutton" commandname = "hiddenpostbuttoncommand" runat = "server" text = "hiddenpostbutton" style = "display: none"/>
</Itemtemplate>
</ASP: templatefield>
<Asp: boundfield datafield = "unitprice" headertext = "unitprice"/>
</Columns>
</ASP: gridview>
Protected void gridview1_rowdatabound (Object sender, gridviewroweventargs E)
{
Button btnhiddenpostbutton = E. Row. findcontrol ("btnhiddenpostbutton") as button;
If (btnhiddenpostbutton! = NULL ){
E. Row. attributes ["onclick"] = string. Format ("javascript: Document. getelementbyid ('{0}'). Click ()", btnhiddenpostbutton. clientid );
// Additional style Definition
E. Row. attributes ["onmouseover"] = "javascript: This. style. Background = 'red '";
E. Row. attributes ["onmouseout"] = "javascript: This. style. Background = ''";
E. Row. attributes ["style"] = "cursor: Pointer ";
E. Row. attributes ["title"] = "click to select the current row ";
}
// If you want to hide the button in a column, set this column to hide. The placeholder <cellindex> indicates the index of this column.
// E. Row. cells [<cellindex>]. attributes ["style"] = "display: none ";
}
Protected void gridview1_rowcommand (Object sender, gridviewcommandeventargs E)
{
Int rowindex =-1;
Gridviewrow ROW = NULL;
Switch (E. commandname ){
Case "hiddenpostbuttoncommand": // template Column
Control primitive control = E. commandsource as control; // It indicates the ibuttoncontrol that triggers the event to maintain uniformity and facilitate subsequent operations. Here we directly convert it to the control base class control.
Row = lateral control. namingcontainer as gridviewrow; // The current row
// How to access cell values
// String TXT = row. cells [0]. text;
// Obtain the label in the template Column
// String LBL = row. findcontrol ("mylabelid") as label;
// Execute more custom operations
//
//
Response. Write (string. Format ("Row {0} of the current gridview version:", row. rowindex + 1 ));
Break;
// Case "command2 ":
// More cases
//
}
}