因为gridview中有好几个隐藏列需要读取数据,所以采用了datakeynames,查阅msdn得到:
如果将某个列字段的 Visible 属性设置为 false,则在 GridView 控件中将不显示该列,该列中的数据也不会往返于客户端。如果希望某个不可见的列中的数据可以进行往返,则向 DataKeyNames 属性添加相应的字段名称。
若要以声明方式设置此属性,请使用以逗号分隔的字段名列表。
故采用了如下代码:
asp文件中(ABCDE为各列datafield):
<asp:GridView ID= "GridView1 " runat= "server " CellPadding= "4 " ForeColor= "#333333 " GridLines= "None " onrowdatabound= "CustomersGridView_RowDataBound " AutoGenerateColumns= "False " DataKeyNames = "A,B,C,D,E " >
<Columns>
………………
<asp:BoundField DataField= "A " Visible =false />
<asp:BoundField DataField= "B " Visible =false />
<asp:BoundField DataField= "C " Visible =false />
<asp:BoundField DataField= "D " Visible =false />
<asp:BoundField DataField= "E " Visible =false />
</Columns> </asp:GridView>
cs文件中:
protected void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (GridView1.DataKeys[0].Value.ToString() == "1 ")
row.Cells[2].Text = "a ";
else if (GridView1.DataKeys[1].Value.ToString() == "1 ")
row.Cells[2].Text = "b ";
else if (GridView1.DataKeys[2].Value.ToString() == "1 ")
row.Cells[2].Text = "c ";
else if (GridView1.DataKeys[3].Value.ToString() == "1 ")
row.Cells[2].Text = "d ";
else row .Cells [2].Text = "e ";
}
运行时,第一条if可以正常运行并赋值,到了第三行的时候,就会出现如下错误提示:
索引超出范围。必须为非负值并小于集合大小。
参数名: index
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。