Szel
Szel

Reputation: 120

DetailsView - Values not changing in ItemUpdating

I have DetailsView binded to one object. When ItemUpdating is called (when I click update) OldValues is empty and NewValues contains old values (are the same as before update).

<asp:DetailsView ID="CustomerDetailsView" runat="server"
    DefaultMode="Edit"
    AutoGenerateRows="false"
    OnItemUpdating="CustomerDetailsView_ItemUpdating"
    >
    <Fields>
        <asp:BoundField DataField="LastName" HeaderText="Last name" ReadOnly="True" />
        <asp:BoundField DataField="FirstName" HeaderText="First name" ReadOnly="True" />
        <%-- Other fields ... --%>
        <asp:CommandField ShowEditButton="true" />
    </Fields>
</asp:DetailsView>

Code behind:

private Customer customer;
protected void Page_Load(object sender, EventArgs e)
{
    using (var context = new CustomersContext())
    {
        customer = context.Logins.First();
    }

    CustomerDetailsView.DataSource = new List<Customer>() { customer };
    CustomerDetailsView.DataBind();
}

protected void CustomerDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
    // e.OldValues.Count == 0
    // e.NewValues["FirstName"] - is same as taken from database
}

Upvotes: 1

Views: 316

Answers (2)

Szel
Szel

Reputation: 120

Stupid me, I was setting new DataSource every time the page was reloaded even if it was post-back.

Should be:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        using (var context = new CustomersContext())
        {
            customer = context.Logins.First();
        }

        CustomerDetailsView.DataSource = new List<Customer>() { customer };
        CustomerDetailsView.DataBind();
    }
}

Can't see OldValues but NewValues looks correct.

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

See this answer: OldValues collection in event "ItemUpdating" of DetailsView is always empty

It appears that this only works if you use the DataSourceID property bound to a data source control.

Upvotes: 2

Related Questions