设置DataKeysName
设置DataKeysName:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="field1,field2,field3"
或者C#:
this.GridView1.DataKeyNames = new string[] { "field1","field2","field3"};
===========================
取值:
string f1 = this.GridView1.DataKeys[0][0].ToString();
string f2 = this.GridView1.DataKeys[0]["field2"].ToString();
string f3 = this.GridView1.SelectedDataKey.Values["field3"];
这有一个例子
this.gvstudent.DataKeyNames = new string[] { "stuSchoolID" };// 设置主键
gvstudent为gridview的ID,定义字段stuSchoolID为主键
获取本行的关键字用如下代码
string stuID = this.gvstudent.DataKeys[e.RowIndex].Values[0].ToString();////获取本行主键
其中为0为关键字所在的列序数
与datagrid有区别,我也被它折腾了半天