Add grid data to database

Asked

Viewed 439 times

6

I have a loan screen and in it I have a datagrid with a checkbox selection and I would like to add in the database only the line selected by the user, as I can do?

imagem da tela de emprestimo

Loan screen code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Projeto_RP
{
    public partial class EmprestimoSaidaForm : Form
    {
        public EmprestimoSaidaForm()
        {
            InitializeComponent();
            preencherlista();                

            txtCodigo.Enabled = false;
            cmbNomeFuncionario.DropDownStyle = ComboBoxStyle.DropDownList;
            dgvLista.AllowUserToAddRows = false;
            dgvLista.AllowUserToDeleteRows = false;
            dgvLista.AllowUserToOrderColumns = false;
            dgvLista.AllowUserToResizeColumns = false;
            dgvLista.AllowUserToResizeRows = false;
            dgvLista.MultiSelect = true;
            dgvLista.ReadOnly = false;

            dgvLista.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvLista.AutoGenerateColumns = false;

        }  

        private void preencherlista()   
        {
            SqlConnection conexao = new SqlConnection();
            conexao.ConnectionString = Properties.Settings.Default.conexao;
            SqlCommand comando = new SqlCommand();
            comando.Connection = conexao;
            comando.CommandText =
                "select Codigo, Nome from Funcionario";

            try
            {
                DataTable tabela = new DataTable();
                SqlDataAdapter adaptador = new SqlDataAdapter();
                adaptador.SelectCommand = comando;
                adaptador.Fill(tabela);
                bsLista.DataSource = tabela;
                cmbNomeFuncionario.DataSource = bsLista;
                cmbNomeFuncionario.DisplayMember = "Nome";
                cmbNomeFuncionario.ValueMember = "Codigo";
                cmbNomeFuncionario.SelectedItem = 0;

                SelecionarCargo(int.Parse(cmbNomeFuncionario.SelectedValue.ToString()));
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Erro ao selecionar dados: " + ex.Message);
            }
        }            

        private void  SelecionarCargo(int codigofuncionario)
        {                                     
            SqlConnection conexao = new SqlConnection();
            conexao.ConnectionString = Properties.Settings.Default.conexao;

            SqlCommand comando = new SqlCommand();
            comando.Connection = conexao;
            comando.CommandText =
                "select f.Codigo, c.Cargo from Funcionario f " +
                "inner join CargoFuncionario c on c.Codigo = f.CodigoCargoFuncionario " +
                "where" +
                 " f.Codigo = @CodigoFuncionario";   


            comando.Parameters.AddWithValue("@CodigoFuncionario", codigofuncionario);

            try
            {
                conexao.Open();
                SqlDataReader leitor = comando.ExecuteReader();
                if (leitor.Read())
                {
                    txtCargo.Text = leitor["Cargo"].ToString(); 
                }
                leitor.Close();

            }
            catch (SqlException ex)
            {
               MessageBox.Show("Erro ao selecionar o registro!" + ex.Message);  
            }
            finally
            {
                conexao.Close();
            }

        }


        protected virtual void pesquisar(string conteudo)
        {
            SqlConnection conexao = new SqlConnection();
            conexao.ConnectionString = Properties.Settings.Default.conexao;
            SqlCommand comando = new SqlCommand();
            comando.Connection = conexao;
            comando.CommandText =
                "select " +
                " m.Nome as NomeMaterial,m.QuantidadeTotal, c.Nome as NomeCategoria " +
                " from Material m " +
                " inner join Categoria c on c.CodigoCategoria = m.CodigoCategoria " +
                " where " +
                " c.Nome like @Nome + '%' ";
            comando.Parameters.AddWithValue("@Nome", conteudo);

            try
            {
                DataTable tabela = new DataTable();
                SqlDataAdapter adaptador = new SqlDataAdapter();
                adaptador.SelectCommand = comando;
                adaptador.Fill(tabela);
                bsLista2.DataSource = tabela;
                dgvLista.DataSource = bsLista2;
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Erro ao pesquisar " + ex.Message);
            }    
        }

        private void cmbNomeUsuario_SelectedIndexChanged(object sender, EventArgs e)
        {   
            if (cmbNomeFuncionario.SelectedIndex > 0)
            {
                int codigo = int.Parse(cmbNomeFuncionario.SelectedValue.ToString());
                SelecionarCargo(codigo);  
            }

        }

        private void btnPesquisar_Click_1(object sender, EventArgs e)
        {
            pesquisar(txtPesquisarCategoriaMaterial.Text);
        }   
    }
}
  • 3

    Welcome to SOPT, your question is very vague, would have [Edit] and pass more information, as well, code used so far, database used, any Framework? This way we can understand better to help you. Thank you.

  • 2

    David still hasn’t programmed the part about adding the grid data because I don’t know

  • All right, I think with the information you’ve added, the guys will be able to help you better :)

  • If I understand your question correctly, I believe the answer you want is in the: Link1

  • @Atiliohenrique Hello, consider accepting my answer if it has been useful to you. If you think she’s incomplete or doesn’t respond to you, make the appropriate comments so I can improve her.

1 answer

2

You can try with the example below.

See that I use a insert normally and the food with the data positioned on the grid.

if (dataGridView1.CurrentRow == null)
    return;

SqlConnectionStringBuilder conexao = new SqlConnectionStringBuilder(Properties.Settings.Default.conexao);
using (var conn = new SqlConnection(conexao.ConnectionString))
{
    conn.Open();
    using (var command = new SqlCommand("insert into produtos (id_categoria, descricao) values(@id_categoria, @descricao)", conn))
    {
        command.Parameters.Add("@id_categoria", SqlDbType.Int).Value = dataGridView1.CurrentRow.Cells["CATEGORIA"].Value;
        command.Parameters.Add("@descricao", SqlDbType.VarChar, 50).Value = dataGridView1.CurrentRow.Cells["NOME_PRODUTO"].Value;
        command.CommandType = CommandType.Text;
        command.ExecuteNonQuery();
        conn.Close();
    }
}

Browser other questions tagged

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