我想更新我的记录,但它在cmd.ExecuteNonQuery()中给出了异常;

时间:2016-05-11 08:24:02

标签: c# asp.net ado.net

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

SqlCommand cmd = new SqlCommand("update Users set Username=@Username,Password=@Password,Name=@Name,Address=@Address,Phone=@Phone,@Email=Email,@RoleId=RoleId", conn);
cmd.Parameters.AddWithValue("@Username", username.Text);
cmd.Parameters.AddWithValue("@Password", password.Text);
cmd.Parameters.AddWithValue("@Name", name.Text);
cmd.Parameters.AddWithValue("@Address", address.Text);
cmd.Parameters.AddWithValue("@Phone", phone.Text);
cmd.Parameters.AddWithValue("@Email", email.Text);
cmd.Parameters.AddWithValue("@RoleId", DropDownList4.SelectedItem);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

2 个答案:

答案 0 :(得分:3)

您不想添加SelectedItem,但它是Value(或文字):

cmd.Parameters.AddWithValue("@RoleId", DropDownList4.SelectedItem.Value);

或通过ListControl.SelectedValue

cmd.Parameters.AddWithValue("@RoleId", DropDownList4.SelectedValue);

little nitpick:将您的控件重命名为更有意义,在本例中为DdlRoleId

答案 1 :(得分:1)

您的查询必须:Email=@Email,代替@Email=Email,RoleId=@RoleId而不是@RoleId=RoleId

 SqlCommand cmd = new SqlCommand("update Users set Username=@Username,Password=@Password,Name=@Name,Address=@Address,Phone=@Phone,Email=@Email,RoleId=@RoleId", conn);