Stefano Altieri
Stefano Altieri

Reputation: 4628

DetailsView bug when binding an empty datatable?

I am using .net 4.5 and I found this odd behaviour:

Markup:

<asp:DetailsView ID="dtvTest" AutoGenerateRows="true" DefaultMode="Insert" runat="server" /> 

Code:

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable("Test");
    dt.Columns.Add("Column", typeof(string));
    // If I uncomment the line it works!
    // dt.Rows.Add("row 1");
    dtvTest.DataSource = dt;
    dtvTest.DataBind(); 
}

the result is

Collection cannot be null. Parameter name: c

thrown on dtvTest.DataBind().

If there is at least one row it works!! (see the commented line).

Any idea on how to fix/work around it?

Many thanks

Upvotes: 4

Views: 640

Answers (1)

Adam
Adam

Reputation: 3914

I have faced the same prob in a recent project of mine I solved it by binding empty rows colleciton as Follows , (btw I compiled it at ur solution and it works just fine)

 protected void Page_Load(object sender, EventArgs e)
    {
       DataTable dt = new DataTable("Test");
        dt.Columns.Add("Column", typeof(string));

        // If I uncomment the line it works!
        // dt.Rows.Add("row 1");

       dt.LoadDataRow(new string[1],true);
        dtvTest.DataSource = dt;

        dtvTest.DataBind();

    }

and also no matter how many columns you add it still works.

regards

Upvotes: 1

Related Questions