1.先创建一个名为Customer的实体类,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Cdm.LinqToXml { public class Customer { public int ID { set; get; } public string Name { set; get; } public string Address { set; get; } public int Age { set; get; } } }
2.在默认页面中添加GridView控件,代码如下:
<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>注意在这里得写了一个得到当前行的主键的事件
onrowcommand="MyGv_RowCommand"
3.后到代码将给Customer这个实体类赋值,代码如下所示:
protected void Page_Load(object sender, EventArgs e) { List<Customer> list = new List<Customer>(); list.Add(new Customer { ID = 1, Name = "caodaiming", Address = "四川", Age = 23 }); list.Add(new Customer { ID = 2, Name = "caodaiming", Address = "四川", Age = 23 }); list.Add(new Customer { ID = 4, Name = "caodaiming", Address = "四川", Age = 23 }); MyGv.DataSource = list; MyGv.DataBind(); }
protected void MyGv_RowCommand(object sender, GridViewCommandEventArgs e) { object s = MyGv.DataKeys[int.Parse(e.CommandArgument.ToString())].Value; Response.Write(s.ToString()); }