DataTable won't DataBind with a DataTable.NewRow()
- by David
Is DataRow.NewRow() insufficient as the only row in a DataTable? I would expect this to work, but it doesn't. It's near the end of my Page_Load inside my If(!Postback) block. gridCPCP is GridView
DataTable dt = new DataTable();
dt.Columns.Add("ID", int.MinValue.GetType());
dt.Columns.Add("Code", string.Empty.GetType());
dt.Columns.Add("Date", DateTime.MinValue.GetType());
dt.Columns.Add("Date2", DateTime.MinValue.GetType());
dt.Columns.Add("Filename", string.Empty.GetType());
//code to add rows
if (dt.Rows.Count > 0)
{
gridCPCP.DataSource = dt;
gridCPCP.DataBind();
}
else
{
dt.Rows.Add(dt.NewRow());
gridCPCP.DataSource = dt;
gridCPCP.DataBind(); //EXCEPTION
int TotalColumns = gridCPCP.Rows[0].Cells.Count;
gridCPCP.Rows[0].Cells.Clear();
gridCPCP.Rows[0].Cells.Add(new TableCell());
gridCPCP.Rows[0].Cells[0].ColumnSpan = TotalColumns;
gridCPCP.Rows[0].Cells[0].Text = "No Record Found";
}
The exception throws on gridCPCP.DataBind() and only when execution reaches the else block. If there were rows added above via dt.Rows.Add(new object[] { ... } binding works.
System.ArgumentOutOfRangeException: Length cannot be less than zero. Parameter name: length