update of rows followed according to selected items in listview

0

We have a table 1, which has building and rooms, building A, room01, room 02 ...., we need to put people in these rooms. These people come from another table (2), which populates the listview. This lvi has checkboxes and is multiselect. What are you gonna do? Selects people by checkboxes and clicks a button to place each person in a room, in sequence. If you select person 1, person 4, person 7, place person 1 in room 1, person 4 in room 2, person 7 in room 3, right on the bench for display on the grid .... I am doing this way:

 private void btnAlocar_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listView2.CheckedItems)
            {
                if (item.Checked == true)
                {
                    int j = listView2.CheckedItems.Count;
                    try
                    {
                        SqlConnection con = new SqlConnection(conexaoString);

                        con.Open();

                        for (int i = 0; i < (j); i++)
                        {
                            var cmd = new SqlCommand(@"UPDATE salas SET
                            nomePessoa=@nomePessoa, cargo=@cargo, idPessoa=@idPessoa WHERE idSala=@idSala", con);

                            cmd.Parameters.AddWithValue("@idSala", Convert.ToInt32(dgvSalas.CurrentRow.Cells["idSala"].Value.ToString()));

                            cmd.Parameters.AddWithValue("@nomePessoa", item.SubItems[0].Text);
                            cmd.Parameters.AddWithValue("@idPessoa", Convert.ToInt32(item.SubItems[3].Text));

                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Erro ao alocar Pessoa: {ex.Message}");
                    }
                    finally
                    {
                        SqlConnection con = new SqlConnection(conexaoString);
                        this.salasTableAdapter.Fill(this.bdDataSet.salas);

                        con.Close();
                        con.Dispose();
                    }
                }
            }

        }

It does the insertion, but only one person, I'm not able to go to the next line and insert the selected ones, where I'm wrong, I can not find the error ....

    
asked by anonymous 06.02.2017 / 23:12

1 answer

0

On line

cmd.Parameters.AddWithValue("@idSala", Convert.ToInt32(dgvSalas.CurrentRow.Cells["idSala"].Value.ToString()));

Where do you update dgvSalas.CurrentRow ? Because it seems to me that you're overwriting the user in that room with every UPDATE ...

    
07.02.2017 / 00:35