指数超出范围。必须是非负数且小于集合的大小

时间:2011-02-19 20:26:42

标签: c# asp.net

我在跟踪我的datakey时收到此错误..我不知道为什么我的datakey索引超出范围..这是我的代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            var dataKeys = GridView1.DataKeys[e.Row.RowIndex];
            dataKeys.Value.ToString();
            Label1.Text = "The key field value for the displayed record is " + dataKeys.Value.ToString();
        }

GridView的标题部分:                                                                                                                                                                                          

        </ItemTemplate>

        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" 
         />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#999999" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

<script language="javascript" type="text/javascript">
    function viewProfile(selectedRowIndex, firstName) {
        //alert(firstName);
        //var customGridView = document.getElementById('<%= CustomGridView.ClientID %>');
        var customGridView = document.getElementById('GridView1');
        if (customGridView) {
            var row = customGridView.rows[parseInt(selectedRowIndex) + 1];
            //var cell = customGridView.rows[parseInt(selectedRowIndex) +   1].cells[0];
            //            alert(row.cells[0].innerHTML);
            //            alert(row.cells[1].innerHTML);
            //            alert(row.cells[2].innerHTML);
            //            alert(row.cells[3].innerHTML);
            //            alert(row.cells[4].innerHTML);
            window.open('detatil.aspx?coaid=' + row.cells[1].innerHTML + '&fnomia=' + row.cells[2].innerHTML, "", "scrollbars=no,height=300,width=300");
        }
    }
</script>

错误是: 指数超出范围。必须是非负数且小于集合的大小。 参数名称:index

1 个答案:

答案 0 :(得分:3)

如果我没记错的话,会针对标头和其他非数据行触发该事件。有一个属性可以知道行的类型。非数据行的索引是-1。添加此项以检查行的类型:

 if (e.Row.RowType == DataControlRowType.DataRow) {
    // do something
 }