Log datagridview data into a table in the database

Asked

Viewed 46 times

0

Good afternoon, you guys! I have a problem with doing a data insertion presented to my datagridview.

I have a table called Events, and it contains all my records, I created another table with the same fields, so that the events would be downloaded when the date is expired.

the problem is this... when I insert the data presented from the first table playing them to the table downloaded events, the data doubles, ie it is taking both the first id and the others. Note:(I am selecting the data from the datagridview line through a menu and clicking.) follows the image.inserir a descrição da imagem aqui

follows my code

private void BaixarDadosAgenda()
    {
        try
        {
            if (DGW_Agenda.Rows.Count > 1)
            {
                cg.con = new SqlConnection(cn.DBconn);
                string cb = "INSERT INTO Eventos_Baixados VALUES (@Nome, @Endereco, @Quadra, @Lote, @Telefone, @Celular, @Data, @Hora, @Email, @Observacao, @Locacao, @Evento, @Estado)";
                cg.con.Open();
                cg.cmd = new SqlCommand(cb);
                cg.cmd.Connection = cg.con;
                for (int i = 0; i <= DGW_Agenda.Rows.Count - 1; i++)
                {       
                    DGW_Agenda.CurrentRow.Cells[0].Value.ToString();
                    DGW_Agenda.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                    DGW_Agenda.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                    DGW_Agenda.MultiSelect = false;
                    cg.cmd.Parameters.Clear();
                    cg.cmd.Parameters.AddWithValue("@Nome", DGW_Agenda.Rows[i].Cells["Nome"].Value);
                    cg.cmd.Parameters.AddWithValue("@Endereco", DGW_Agenda.Rows[i].Cells["Endereco"].Value);
                    cg.cmd.Parameters.AddWithValue("@Quadra", DGW_Agenda.Rows[i].Cells["Quadra"].Value);
                    cg.cmd.Parameters.AddWithValue("@Lote", DGW_Agenda.Rows[i].Cells["Lote"].Value);
                    cg.cmd.Parameters.AddWithValue("@Telefone", DGW_Agenda.Rows[i].Cells["Telefone"].Value);
                    cg.cmd.Parameters.AddWithValue("@Celular", DGW_Agenda.Rows[i].Cells["Celular"].Value);
                    cg.cmd.Parameters.AddWithValue("@Data", DGW_Agenda.Rows[i].Cells["Data"].Value);
                    cg.cmd.Parameters.AddWithValue("@Hora", DGW_Agenda.Rows[i].Cells["Hora"].Value);
                    cg.cmd.Parameters.AddWithValue("@Email", DGW_Agenda.Rows[i].Cells["Email"].Value);
                    cg.cmd.Parameters.AddWithValue("@Observacao", DGW_Agenda.Rows[i].Cells["Observacao"].Value);
                    cg.cmd.Parameters.AddWithValue("@Locacao", DGW_Agenda.Rows[i].Cells["Locacao"].Value);
                    cg.cmd.Parameters.AddWithValue("@Evento", DGW_Agenda.Rows[i].Cells["Evento"].Value);
                    cg.cmd.Parameters.AddWithValue("@Estado", DGW_Agenda.Rows[i].Cells["Estado"].Value);
                    cg.cmd.ExecuteNonQuery();
                    DGW_Agenda.Rows.Clear();

                }
                cg.con.Close();
                st1 = Lbl_Usuario.Text;
                st2 = "Nova Locacão Baixada '" + TB_Nome.Text;
                cf.LogFunc(st1, DateTime.Now, st2);
                LogEvento.GravarLog("'Locação Baixada com Sucesso! :  = '" + TB_Nome.Text + "'Usuário'" + Lbl_Usuario.Text.ToString());
                Reset();
                BTN_Cadastrar.Enabled = false;

                MessageBox.Show("Locação Baixada Com Sucesso !", "Locação", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BT_BaixaAgenda_Click(object sender, EventArgs e)
    {


        if (MessageBox.Show("Deseja dar baixa nessa Locação?", "Aviso do Sistema", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {

            BaixarDadosAgenda();
        }

    }

From now on I thank you for your strength!

  • You can select more than one line ?

  • No! the idea is to select one line at a time. I even did a test on my for my routine leaving it like this. for (int i = 0; i <= Dgw_agenda.SelectedRows.Count - 1; i++) But to no avail!

  • With the for has no way to work

2 answers

0

I managed to solve the problem, guys!

 private void BaixarDadosAgenda()
        {
            try
            {
                var row = DGW_Agenda.CurrentRow;
                if (row != null)
                {
                    //ao meu ver essas configurações seriam ao carregar a tela
                    DGW_Agenda.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                    DGW_Agenda.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                    DGW_Agenda.MultiSelect = false;

                    cg.con = new SqlConnection(cn.DBconn);
                    string cb = "INSERT INTO Eventos_Baixados VALUES (@Nome, @Endereco, @Quadra, @Lote, @Telefone, @Celular, @Data, @Hora, @Email, @Observacao, @Locacao, @Evento, @Estado)";
                    cg.con.Open();
                    cg.cmd = new SqlCommand(cb);
                    cg.cmd.Connection = cg.con;
                    //for (int i = 0; i <= DGW_Agenda.SelectedRows.Count - 1; i++)
                    {
                        cg.cmd.Parameters.Clear();
                        cg.cmd.Parameters.AddWithValue("@Nome", row.Cells["Nome"].Value);
                        cg.cmd.Parameters.AddWithValue("@Endereco", row.Cells["Endereco"].Value);
                        cg.cmd.Parameters.AddWithValue("@Quadra", row.Cells["Quadra"].Value);
                        cg.cmd.Parameters.AddWithValue("@Lote", row.Cells["Lote"].Value);
                        cg.cmd.Parameters.AddWithValue("@Telefone", row.Cells["Telefone"].Value);
                        cg.cmd.Parameters.AddWithValue("@Celular", row.Cells["Celular"].Value);
                        cg.cmd.Parameters.AddWithValue("@Data", row.Cells["Data"].Value);
                        cg.cmd.Parameters.AddWithValue("@Hora", row.Cells["Hora"].Value);
                        cg.cmd.Parameters.AddWithValue("@Email", row.Cells["Email"].Value);
                        cg.cmd.Parameters.AddWithValue("@Observacao", row.Cells["Observacao"].Value);
                        cg.cmd.Parameters.AddWithValue("@Locacao", row.Cells["Locacao"].Value);
                        cg.cmd.Parameters.AddWithValue("@Evento", row.Cells["Evento"].Value);
                        cg.cmd.Parameters.AddWithValue("@Estado", row.Cells["Estado"].Value);
                        cg.cmd.ExecuteNonQuery();
                    }
                    cg.con.Close();

                    DGW_Agenda.Refresh();

                    st1 = Lbl_Usuario.Text;
                    st2 = "Nova Locacão Baixada '" + TB_Nome.Text;
                    cf.LogFunc(st1, DateTime.Now, st2);
                    LogEvento.GravarLog("'Locação Baixada com Sucesso! :  = '" + TB_Nome.Text + "'Usuário'" + Lbl_Usuario.Text.ToString());
                    Reset();
                    BTN_Cadastrar.Enabled = false;

                    MessageBox.Show("Locação Baixada Com Sucesso !", "Locação", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

0

Your mistake was creating the loop, there’s no need to use a loop if you want to grab a line, it’s iterating and it’s inserting all the rows into the database.

The solution would be like this:

try
    {
        if (DGW_Agenda.Rows.Count > 1)
        {
          if (DGW_Agenda.SelectedRows.Count > 0) // Para assegurar que existe linha selecionada
             {
            cg.con = new SqlConnection(cn.DBconn);
            string cb = "INSERT INTO Eventos_Baixados VALUES (@Nome, @Endereco, @Quadra, @Lote, @Telefone, @Celular, @Data, @Hora, @Email, @Observacao, @Locacao, @Evento, @Estado)";
            cg.con.Open();
            cg.cmd = new SqlCommand(cb);
            cg.cmd.Connection = cg.con;

               int i=DGW_Agenda.CurrentRow.Index; // pega o índice da linha selecionada
                DGW_Agenda.CurrentRow.Cells[0].Value.ToString();
                DGW_Agenda.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                DGW_Agenda.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                DGW_Agenda.MultiSelect = false;
                cg.cmd.Parameters.Clear();
                cg.cmd.Parameters.AddWithValue("@Nome", DGW_Agenda.Rows[i].Cells["Nome"].Value);
                cg.cmd.Parameters.AddWithValue("@Endereco", DGW_Agenda.Rows[i].Cells["Endereco"].Value);
                cg.cmd.Parameters.AddWithValue("@Quadra", DGW_Agenda.Rows[i].Cells["Quadra"].Value);
                cg.cmd.Parameters.AddWithValue("@Lote", DGW_Agenda.Rows[i].Cells["Lote"].Value);
                cg.cmd.Parameters.AddWithValue("@Telefone", DGW_Agenda.Rows[i].Cells["Telefone"].Value);
                cg.cmd.Parameters.AddWithValue("@Celular", DGW_Agenda.Rows[i].Cells["Celular"].Value);
                cg.cmd.Parameters.AddWithValue("@Data", DGW_Agenda.Rows[i].Cells["Data"].Value);
                cg.cmd.Parameters.AddWithValue("@Hora", DGW_Agenda.Rows[i].Cells["Hora"].Value);
                cg.cmd.Parameters.AddWithValue("@Email", DGW_Agenda.Rows[i].Cells["Email"].Value);
                cg.cmd.Parameters.AddWithValue("@Observacao", DGW_Agenda.Rows[i].Cells["Observacao"].Value);
                cg.cmd.Parameters.AddWithValue("@Locacao", DGW_Agenda.Rows[i].Cells["Locacao"].Value);
                cg.cmd.Parameters.AddWithValue("@Evento", DGW_Agenda.Rows[i].Cells["Evento"].Value);
                cg.cmd.Parameters.AddWithValue("@Estado", DGW_Agenda.Rows[i].Cells["Estado"].Value);
                cg.cmd.ExecuteNonQuery();
                DGW_Agenda.Rows.Clear();


            cg.con.Close();
            st1 = Lbl_Usuario.Text;
            st2 = "Nova Locacão Baixada '" + TB_Nome.Text;
            cf.LogFunc(st1, DateTime.Now, st2);
            LogEvento.GravarLog("'Locação Baixada com Sucesso! :  = '" + TB_Nome.Text + "'Usuário'" + Lbl_Usuario.Text.ToString());
            Reset();
            BTN_Cadastrar.Enabled = false;

            MessageBox.Show("Locação Baixada Com Sucesso !", "Locação", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
      }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void BT_BaixaAgenda_Click(object sender, EventArgs e)
{


    if (MessageBox.Show("Deseja dar baixa nessa Locação?", "Aviso do Sistema", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {

        BaixarDadosAgenda();
    }

}
  • I even understood what you meant Joypeter, the problem and that he was making the insert of all the records, and what I need that would be one at a time according to the expired date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.