3

I am creating a web app, and within this app I want to allow users to update their user information (first name, last name, email, phone number, company name) or change their password. When the page loads, their current information is entered into the text boxes. My problem is that I don't know how to apply the changes the user makes. My code currently looks like this:

    DataClasses1DataContext context = new DataClasses1DataContext();
    User user = new User();


    protected void Page_Load(object sender, EventArgs e)
    {
        string usr = Session["SessionUserName"].ToString();

        user = (from u in context.Users
                    where u.username.Equals(usr)
                    select u).FirstOrDefault();

        txtFName.Text = user.firstName;
        txtLName.Text = user.lastName;
        txtCompany.Text = user.companyName;
        txtEmail.Text = user.email;
        txtPhone.Text = user.phoneNumber;


    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {

        using (DataClasses1DataContext context2 = new DataClasses1DataContext())
        {
            User nUser = (from u in context2.Users
                          where u.username == user.username
                          select u).SingleOrDefault();

            if (nUser != null)
            {
                //make the changes to the user
                nUser.firstName = txtFName.Text;
                nUser.lastName = txtLName.Text;
                nUser.email = txtEmail.Text;
                if (!String.IsNullOrEmpty(txtPhone.Text))
                    nUser.phoneNumber = txtPhone.Text;
                if (!String.IsNullOrEmpty(txtCompany.Text))
                    nUser.companyName = txtCompany.Text;
                nUser.timeStamp = DateTime.Now;
            }


            //submit the changes
            context2.SubmitChanges();

            Response.Redirect("Projects.aspx");

        }

This doesn't give me any errors, but it also doesn't apply the changes. Some google searching led me to add

context2.Users.Attach(nUser);

but that gave me the error message: System.InvalidOperationException: Cannot attach an entity that already exists. So I tried

context2.Users.Attach(nUser, true); 

and I got the same error message.

Looking at google some more I found information about detaching an entity first, but that information was about 3 years old and doesn't appear to be valid anymore (as context.Detach or context.Users.Detach are not options and give me build errors if I try to use them). Other error message I received (that I don't remember how I got to honestly) suggested that I change the update policy so I set all fields under the Users class to never for the update policy. There was suggestions to deserialize and then serialize the data again, but I couldn't find any information on how to do that. Any help would be appreciated.

EDIT: Changed the code due to some suggestions below, but it's still not working. I do not get any error messages, but the data is not being saved.

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string usr = Session["SessionUserName"].ToString();

            user = (from u in context.Users
                    where u.username.Equals(usr)
                    select u).FirstOrDefault();

            txtFName.Text = user.firstName;
            txtLName.Text = user.lastName;
            txtCompany.Text = user.companyName;
            txtEmail.Text = user.email;
            txtPhone.Text = user.phoneNumber;
        }  

    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {



                //make the changes to the user
                user.firstName = txtFName.Text;
                user.lastName = txtLName.Text;
                user.email = txtEmail.Text;
                if (!String.IsNullOrEmpty(txtPhone.Text))
                    user.phoneNumber = txtPhone.Text;
                if (!String.IsNullOrEmpty(txtCompany.Text))
                    user.companyName = txtCompany.Text;
                user.timeStamp = DateTime.Now;
                //submit the changes
            context.SubmitChanges();

            Response.Redirect("Projects.aspx");

      }
2
  • When you debug and step through, do you see the correct values being assigned? or do the .Text properties still contain the original values assigned? Commented Apr 16, 2012 at 13:51
  • The values are being assigned correctly, but the username was missing. I put what I did to solve it below. Commented Apr 16, 2012 at 14:03

1 Answer 1

1

This is happening because your writing the same info back to those textboxes before the update. All you need to do is change your page_load to this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string usr = Session["SessionUserName"].ToString();

        user = (from u in context.Users
                where u.username.Equals(usr)
                select u).FirstOrDefault();

        txtFName.Text = user.firstName;
        txtLName.Text = user.lastName;
        txtCompany.Text = user.companyName;
        txtEmail.Text = user.email;
        txtPhone.Text = user.phoneNumber;
    }
}

The page_load is executing before your update. Therefore, it is reassigning the original values and then updating them with the same. Hope this helps! Good Luck!

EDIT: Changes made after question was updated:

Change your entire code to this. I have also added some need checking that you should be handling and removed your global variables from the top:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["SessionUserName"] != null)
        {
            string usr = Session["SessionUserName"].ToString();

            DataClasses1DataContext context = new DataClasses1DataContext();
            User user = (from u in context.Users
                         where u.username.Equals(usr)
                         select u).FirstOrDefault();

            if (user != null)
            {
                txtFName.Text = user.firstName;
                txtLName.Text = user.lastName;
                txtCompany.Text = user.companyName;
                txtEmail.Text = user.email;
                txtPhone.Text = user.phoneNumber;
            }
            else
            {
                //--- handle user not found error
            }
        }
        else
        {
            //--- handle session is null
        }
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    if (Session["SessionUserName"] != null)
    {
        string usr = Session["SessionUserName"].ToString();

        try
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            User nUser = (from u in context.Users
                          where u.username.Equals(usr)
                          select u).FirstOrDefault();

            //make the changes to the user
            nUser.firstName = txtFName.Text;
            nUser.lastName = txtLName.Text;
            nUser.email = txtEmail.Text;
            if (!String.IsNullOrEmpty(txtPhone.Text))
                nUser.phoneNumber = txtPhone.Text;
            if (!String.IsNullOrEmpty(txtCompany.Text))
                nUser.companyName = txtCompany.Text;
            nUser.timeStamp = DateTime.Now;

            //submit the changes
            context.SubmitChanges();

            Response.Redirect("Projects.aspx");
        }
        catch (Exception ex)
        {
            //--- handle update error
        }
    }
    else
    {
        //--- handle null session error
    }
}

That should work out for you. Let me know! Good Luck!

Sign up to request clarification or add additional context in comments.

3 Comments

That's essentially what I did...minus all the if tests and the try/catch block. And it worked wonderfully, thank you!
Glad it worked out, you should definitely consider using the error catching. If you don't use it, your app could throw server errors.
I added the error catching in. Now I just have to actually put the code in for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.