1. Create an object class named customer first. The Code is as follows:
using system; using system. collections. generic; using system. using system. web; namespace CDM. linqtoxml { public class customer { Public int ID { set ; Get ;}< span style =" color: blue "> Public String name { set ; Get ;}< span style =" color: Blue "> Public String address { set ; Get ;}< span style =" color: blue "> Public int Age { set ; Get ;}}
2. Add the gridview control on the default page. The Code is as follows:
< Form ID = "Form1" Runat = "Server"> < Div > < ASP : Gridview ID = "Mygv" Runat = "Server" Autogeneratecolumns = "False" Datakeynames = "ID" Onrowcommand = "Mygv_rowcommand"> < Columns > < ASP : Commandfield Causesvalidation = "False" Showselectbutton = "True" Buttontype = "Image" Selectimageurl = "~ /Right.gif "/> < ASP : Boundfield Datafield = "ID" Headertext = "ID"/> < ASP : Boundfield Datafield = "Name" Headertext = "Name"/> < ASP : Boundfield Datafield = "Address" Headertext = "Address"/> < ASP : Boundfield Datafield = "Age" Headertext = "Age"/> </ Columns > </ ASP : Gridview > </ Div > </ Form >
Note that you have to write an event to get the primary key of the current row.
Onrowcommand= "Mygv_rowcommand"
3. The Code will assign values to the object class "customer". The Code is as follows:
Protected void Page_load ( Object Sender, Eventargs E ){ List <Customer > List = New List < Customer > (); List. Add ( New Customer {Id = 1, name = "Caodaiming" , Address = "Sichuan" , Age = 23}); list. Add ( New Customer {Id = 2, name = "Caodaiming" , Address ="Sichuan" , Age = 23}); list. Add ( New Customer {Id = 4, name = "Caodaiming" , Address = "Sichuan" , Age = 23}); mygv. datasource = List; mygv. databind ();}
4. Add the primary key event code for the current row as follows:
Protected voidMygv_rowcommand (ObjectSender,GridviewcommandeventargsE ){ObjectS = mygv. datakeys [Int. Parse (E. commandargument. tostring ()]. value; response. Write (S. tostring ());}
5. Shows the running effect: