0

I am trying to get data from the rows that are generated in a GridView. Here is my table:

enter image description here

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

The output is:

Hours 6.25 3 5 4  

I however need the data from the date column. But when I do:

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

I get the following error:

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

I don't understand what I am doing wrong.

David Tunnell
  • 7,252
  • 20
  • 66
  • 124

1 Answers1

1

Getting the date using cell index is very fragile. It only throws exception at run time.

You can easily achieve the same result by casting DataItem to appropiate object.

enter image description here

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;
    }
}
Win
  • 61,100
  • 13
  • 102
  • 181
  • The table is being pulled from a SQL server database. I created an instance of the data Data and did the following: if (e.Row.RowType == DataControlRowType.DataRow) { var data = e.Row.DataItem as Data; var date = data.Date; System.Diagnostics.Debug.WriteLine(data); } and got no output – David Tunnell Jul 11 '13 at 16:34
  • Please look at this answers regarding how to cast to DataItem to DataRowView - http://stackoverflow.com/a/16737479/296861 – Win Jul 11 '13 at 16:39