0

我正在尝试从 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

我不明白我做错了什么。

4

1 回答 1

1

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

您可以通过将DataItem转换为适当的对象轻松实现相同的结果。

在此处输入图像描述

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;
    }
}
于 2013-07-11T16:22:47.443 回答