NET 2.0 uses sqldatasource and gridview. linkbuttom must be placed in templatefield, but the gridview does not have itemcommand event. Instead, rowcommand event is used.
14 protected void page_load (Object sender, eventargs e ){
15 if (! Ispostback)
16 gridview1_databind ();
17}
18
19 protected void gridview1_databind (){
20 sqldatasource1.connectionstring = @ "Data Source =. \ sqlexpress; initial catalog = pubs; Integrated Security = true ";
21 sqldatasource1.selectcommand = "select top 10" +
22 "fname," +
23 "lname" +
24 "from employee ";
25 gridview1.performanceid = sqlperformance1.id;
26 gridview1.datakeynames = new string [] {"lname "};
27 gridview1.autogeneratecolumns = false;
28}
29
30 Protected void gridview1_rowcommand (Object sender, gridviewcommandeventargs e ){
31 if (E. commandname = "select "){
32 int rowindex = (gridviewrow) (linkbutton) E. commandsource). namingcontainer). rowindex;
33 label1.text = gridview1.datakeys [rowindex]. value. tostring ();
34}
35}
36 </SCRIPT>
37
38 <HTML xmlns = "http://www.w3.org/1999/xhtml">
39
40 <title> untitled page </title>
41
42 <body>
43 <Form ID = "form1" runat = "server">
44 <div>
45 <asp: gridview id = "gridview1" runat = "server" onrowcommand = "gridview1_rowcommand">
46 <columns>
47 <asp: templatefield headertext = "first name">
48 <itemtemplate>
49 <asp: linkbutton id = "linkbutton1" runat = "server" commandname = "select" text = '<% # eval ("fname") %>'> </ASP: linkbutton>
50 </itemtemplate>
51 </ASP: templatefield>
52 </columns>
53 </ASP: gridview>
54 </div>
55 <asp: Label id = "label1" runat = "server"> </ASP: Label>
56 <asp: sqldatasource id = "sqldatasource1" runat = "server"> </ASP: sqldatasource>
57 </form>
58 </body>
59
The most understandable is 32 rows.
Int rowindex = (gridviewrow) (linkbutton) E. commandsource). namingcontainer). rowindex;
E. commandsource splits the following linkbutton. However, if the response is an object, you have to convert it into a linkbutton, but what we want to know is rowindex, the linkbutton is included in gridviewrow, so the current gridviewrow is returned through namingcontainer, but the result is control. Therefore, the rowindex property can only be available after being merged into gridviewrow.