Friday, March 23, 2012

saving data into database

Im using MS visual web developer. I have created a website and used the database they set up by using admin tools. One page requires the take the users comment and to save it into the database. I've tried a formview and connected it to the database which worked. the problem is i cannot save whatever the user types into the textbox.

{insert query didnt work with this set up }

INSERT INTO aspnet_Membership(Comment) VALUES ('CommentTextBox.Text')

Error: cannot set userId or to null. and if i make it allow nulls its going to move on to the next column.

I would appreciate some help please. Thank you in advance.

hi

you said that the error is "cannot set userId or to null",i think in your database userid field might be primary key or you might set it is not null,that's why this error will occur.so you have to pass userid value also in the insert query,you said if you allow null it's going to next row for value saving. yes it will move to next row if you used insert query,if you want add comment only in already created row means,you have to write update query like this

"UPDATE aspnet_Membership SET Comment='CommentTextBox.Text' WHERE userId=some userid;

if it would not clear your doubts plz reply me

|||

Can you post the structure of the table aspnet_membership?

Based on your error, it seems to have a not null field userID. If yes, the insert should be (assuming UserID field stores the name of the user)

INSERT INTO aspnet_Membership(UserID, Comment) VALUES ( user.Identity.Name, CommentTextBox.Text)

A piece of advice,

This type of insert is dangerous as it allows for sql injection attack. Use a parameterized insert instead.

|||

I think you misunderstood me you said, "you said if you allow null it's going to next row for value saving." but what happens is when i check the box to allow null it will go to the next column to complain and say it doesnt allow nulls and this table has relationship :) to other tables. Thank you SOO much for helping or trying.

|||

Himagedassad ,

I would recommend you useMembership.UpdateUser Method instead of manipulate the database directly. You can create a new membershipUser and assign the current user's userId to this new instance, also, pass the text value in CommentTextBox to this membershipuserinstance and call Membership.UpdateUser. It's a much recommended way by microsoft.

BTW, as rajakec has suggested you, you cannot use INSERT INTO command that way. The UserId is the primary key of membership table, thus not allow null--> that's the exact reason you are getting such errors.

Check the following link for more info. on Membership.UpdateUser:http://msdn2.microsoft.com/en-us/library/system.web.security.membership.updateuser(VS.80).aspx

Hope my suggestion helps

No comments:

Post a Comment