0

I am trying to save a username to a database after clicking the Add User button but having trouble this is what i have:

 private void btnAddUser_Click(object sender, EventArgs e)
    {
        using (var db = new DocMgmtDataContext())
        {
            User user = new User()
            {
                FullName = (NewUserName.Text as User).ID
            };
            db.Users.InsertOnSubmit(user);
            db.SubmitChanges();
        }
        UpdateUserLists();
    }

it is not liking the as User part.

MY SOLUTION

FullName = NewUserName.Text, ID = Guid.NewGuid()

3 Answers 3

2

NewUserName.Text is probably of type String and you're trying to cast it to a User. This will certainly not work.

Try this:

 FullName = NewUserName.Text
Sign up to request clarification or add additional context in comments.

3 Comments

I noticed that after i made this change - it worked and the user was added successfully but when i went to add another user it gave me an error that i cannot add duplicate user (different names) but as i looked into the database i noticed the user i added has id value of 00000... and i think every user i am adding it is trying to assign 000000... as well.
If you want to autogenerate an ID for each user, make the ID column of the database table an IDENTITY column, assuming you're using SQL Server.
so making the change in the database is the only solution? i just want to make sure because i wasn't the one creating it and want to make sure to ask before making the proper changes
1

change this

 FullName = (NewUserName.Text as User).ID

To this

 FullName = NewUserName.Text

Comments

1

I assume that from your NewUserName Textbox you want to get user FullName so change your code to this:

private void btnAddUser_Click(object sender, EventArgs e)
{
    using (var db = new DocMgmtDataContext())
    {
         User user = new User()
         {
                FullName = NewUserName.Text //fix
         };
         db.Users.InsertOnSubmit(user);
         db.SubmitChanges();
    }
}

Comments

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.