Update
In editing the question I have spotted my own mistake (invalid cast to a string.)
Many thanks to all, all suggestions most helpful.
Original Question
I have an .aspx page with a GridView, databound to an ObjectDataSource which is filled with a DataSet containing a DataTable.
When handling the RowDataBound callback on the GridView however, I am unable to reference columns in the underlying dataset by column name, they just return an object of type DBNull. So:
protected void accountsGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// One way:
// This works, but uses a hard coded column index which
// I want to replace.
if (e.Row.Cells[11].Text != " ")
{
// Apply certain styles to the row depending on
// the contents of the cell.
}
// Another way. This doesn't work - "date" is always DBNull.
DataRow row = (e.Row.DataItem as DataRowView).Row;
DateTime date;
if(!Convert.IsDBNull(row["date"]))
{
date = (DateTime)row["date"]);
if (date < SomeConstantDate)
{
// Apply certain styles to the row depending on
// the contents of the cell.
}
}
}
}
So specifically:
row["date"]returns an object of typeDBNull.row[11]returns aDateTime.row.Table.Columns["date"]returns a validDataColumnrow[row.Table.Columns["date"]]returns an object of typeDBNull.
Can anyone suggest why this might be happening?
Setup
<asp:GridView ID="GV" runat="server" DataSourceID="ODS"
AutoGenerateColumns="false"
... snip ...
onrowdatabound="GV_RowDataBound" >
<Columns> ... </Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ODS" runat="server"
SelectMethod="getData"
... snip ...
</asp:ObjectDataSource>
there are a few things to consider.
e.Row.Cellsis referring to the formatted output, not the object itself. instead try this