从多个文本框更新数据库

时间:2017-02-03 08:00:17

标签: c# sql database

这是我的更新按钮的代码,它应该根据文本框的条目值更新数据库。当用户在datagridview上选择一行时,我将填充文本框。我希望用户只需单击该行然后更改文本框文本,然后单击更新。但我无法使其工作。所有评论都很有帮助。拍摄。

private void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtOgrenciNo.Text.Length != 0 && txtAd.Text.Length != 0 && txtSoyad.Text.Length != 0 && txtEmail.Text.Length != 0 && txtTelefon.Text.Length != 0)
            {
                string query ="UPDATE ogrenci(studentId,name,lname,email,phone) SET (studentId=@studentId,name@name,lname=@lname,email=@email,phone=@phone) WHERE studentId=@studentId";
                string query1 = "UPDATE loginusers(username,upassword) SET (username=@email,upassword=@phone) WHERE username=@email";
                using (connection = new SqlConnection(connectionString))
                using (SqlCommand command = new SqlCommand(query, connection))
                using (SqlCommand cmd = new SqlCommand(query1, connection))
                {
                    connection.Open();
                    cmd.Parameters.AddWithValue("@emailVal", txtEmail.Text);
                    cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
                    command.Parameters.AddWithValue("@studentId", txtStudentId.Text);
                    command.Parameters.AddWithValue("@name", txtName.Text);
                    command.Parameters.AddWithValue("@lname", txtLname.Text);
                    command.Parameters.AddWithValue("@email", txtEmail.Text);
                    command.Parameters.AddWithValue("@phone", txtPhone.Text);
                    cmd.ExecuteNonQuery();
                    command.ExecuteNonQuery();
                    populateGrid();
                }
            }
            else
            {
                MessageBox.Show("Student Information can not be blank","Alert",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }
        catch (Exception)
        {
            MessageBox.Show("Please enter different student info", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

1 个答案:

答案 0 :(得分:2)

更改update次查询,在(parameters)

后删除table name

更改此行

string query ="UPDATE ogrenci(studentId,name,lname,email,phone) SET (studentId=@studentId,name@name,lname=@lname,email=@email,phone=@phone) WHERE studentId=@studentId";
string query1 = "UPDATE loginusers(username,upassword) SET (username=@email,upassword=@phone) WHERE username=@email";

到此

string query ="UPDATE ogrenci SET  studentId=@studentId,name@name,lname=@lname,email=@email,phone=@phone WHERE studentId=@studentId";
string query1 = "UPDATE loginusers SET username=@email,upassword=@phone WHERE username=@email";