DataTable won't DataBind with a DataTable.NewRow()
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
开发者_JAVA百科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
Exception is because of the empty row. You should:
- Make a new
.NewRow()
- Add desired fields
- Add into the DataTable.
-
myRow = dt.NewRow();
myRow["ID"] = 1001;
myRow["Code"] = "YourCode";
dt.Rows.Add(myRow);
gridCPCP.DataSource = dt;
gridCPCP.DataBind();
Sorry that I'm not answering your exact question but checking the code on the else
block I wonder... why don't you use the
GridView.EmptyDataTemplate for the case you query returned no data?
This doesn't really answer the question either, but my solution would probably be to not bother calling the DataBind() method at all if there are no rows, and put the error message in a asp:Literal outside of the GridView, which gets shown only if there are no rows.
精彩评论