Add grid data to the bank

6

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

Loanscreencode:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceProjeto_RP{publicpartialclassEmprestimoSaidaForm:Form{publicEmprestimoSaidaForm(){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;}privatevoidpreencherlista(){SqlConnectionconexao=newSqlConnection();conexao.ConnectionString=Properties.Settings.Default.conexao;SqlCommandcomando=newSqlCommand();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);
        }   
    }
}
    
asked by anonymous 19.01.2016 / 17:10

1 answer

2

You can try with the example below.

See that I use a insert normally and the feed 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();
    }
}
    
23.05.2016 / 16:35