行返回时Gridview索引超出范围

时间:2013-09-20 14:57:50

标签: c# asp.net

我想更改gridview中第一行的CSS样式:

protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        GridViewRow firstRow = hoursReportGridView.Rows[0];
        firstRow.CssClass = "firstRow";
    }
}

我收到此错误:索引超出范围。必须是非负数且小于集合的大小。

在每个实例中都返回了多行,因此我不理解问题enter image description here

3 个答案:

答案 0 :(得分:3)

我假设第一行存在于GridView.Rows RowDataBound之后。所以你可以在以后访问它。所以我会改用DataBound。请注意,您还要为每一行设置第一行,因为网格中的每一行都会触发RowDataBound

protected void hoursReportGridView_DataBound(object sender, EventArgs e)
{
    if(this.hoursReportGridView.Rows.Count > 0)
        hoursReportGridView.Rows[0].CssClass = "firstRow";
}

另一种选择是使用GridViewRow.RowIndex

protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if(e.Row.RowIndex == 0)
            e.Row.CssClass = "firstRow";
    }
}

答案 1 :(得分:1)

试试这个:

protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex == 0)
        {
            e.Row.CssClass = "firstRow";

    }
}

答案 2 :(得分:1)

为什么要在每一行的数据绑定上执行此操作?

只需在Page_Load中执行此操作:

// Run this after any binding calls, obviously
if(hoursReportGridView.Rows.Count > 0)
{
    hoursReportGridView.Rows[0].CssClass = "firstRow";
}