C# 在OnRowDataBound调用期间检索单元格会导致越界异常

C# 在OnRowDataBound调用期间检索单元格会导致越界异常,c#,asp.net,gridview,C#,Asp.net,Gridview,我试图从GridView中生成的行中获取数据。这是我的桌子: protected void viewStoryTime_OnRowDataBound(Object sender, GridViewRowEventArgs e) { System.Diagnostics.Debug.WriteLine(e.Row.Cells[0].Text); } 输出为: 小时数 6.25 3. 5. 4. 但是,我需要日期列中的数据。但当我这样做的时候: protected void viewS

我试图从GridView中生成的行中获取数据。这是我的桌子:

protected void viewStoryTime_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.Row.Cells[0].Text);
}

输出为:

小时数 6.25 3. 5. 4.

但是,我需要日期列中的数据。但当我这样做的时候:

protected void viewStoryTime_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.Row.Cells[2].Text);
}
我得到以下错误:

System.ArgumentOutOfRangeException was unhandled by user code
Specified argument was out of the range of valid values.
Parameter name: index

我不明白我做错了什么。

使用单元格索引获取日期非常脆弱。它只在运行时抛出异常

通过对对象进行适当的强制转换,可以很容易地获得相同的结果

public class  Data
{
    public decimal Hours { get; set; }
    public string Notes { get; set; }
    public DateTime Date { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = new List<Data>
        {
            new Data { Hours = 6.25m, Notes = "One", Date = DateTime.Parse("07/11/2013")},
            new Data { Hours = 3m, Notes = "Two", Date = DateTime.Parse("07/11/2013")},
            new Data { Hours = 5m, Notes = "Three", Date = DateTime.Parse("07/11/2013")},
            new Data { Hours = 4m, Notes = "Four", Date = DateTime.Parse("01/01/1900")}
        };
    GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {         
        var data = e.Row.DataItem as Data; 
        var date = data.Date;

        // Cast to DataRowView if your datasource is DataTable or DataSet
        // var rowView = (DataRowView)e.Row.DataItem;
    }
}

公共类数据
{
公共十进制小时数{get;set;}
公共字符串注释{get;set;}
公共日期时间日期{get;set;}
}
受保护的无效页面加载(对象发送方、事件参数e)
{
GridView1.DataSource=新列表
{
新数据{Hours=6.25m,Notes=“One”,Date=DateTime.Parse(“07/11/2013”)},
新数据{Hours=3m,Notes=“Two”,Date=DateTime.Parse(“07/11/2013”)},
新数据{Hours=5m,Notes=“Three”,Date=DateTime.Parse(“07/11/2013”)},
新数据{Hours=4m,Notes=“Four”,Date=DateTime.Parse(“01/01/1900”)}
};
GridView1.DataBind();
}
受保护的void GridView1_RowDataBound(对象发送方,GridViewRowEventArgs e)
{
如果(e.Row.RowType==DataControlRowType.DataRow)
{         
var data=e.Row.DataItem作为数据;
var date=data.date;
//如果数据源是DataTable或DataSet,则强制转换为DataRowView
//var rowView=(DataRowView)e.Row.DataItem;
}
}

正在从SQL server数据库中提取该表。我创建了一个数据数据实例,并执行了以下操作:if(e.Row.RowType==DataControlRowType.DataRow){var data=e.Row.DataItem作为数据;var date=data.date;System.Diagnostics.Debug.WriteLine(data);}并且没有得到任何输出请查看关于如何将DataItem转换为DataRowView的答案-